英文:
How do I read a word from a line from a file with multiple lines?
问题
我正在尝试打开一个文件,读取文件中的行,然后从每一行读取单词。我知道我需要使用getline()以及istringstream,但是参数让我感到困惑。
这是我的代码,但我不确定它是否正确:
getline(file, line);
istringstream ss(line);
ss >> word;
totalWords++;
英文:
I'm trying to open a file, read the lines in a file, then read the words from each line. I know I need to use getline() as well as istringstream but I am getting confused on the parameters.
this is what I havem but I'm not sure if it's correct
getline(file, line);
istringstream ss(word);
ss >> word;
totalWords++;
答案1
得分: 2
使用std::getline
在循环中逐行读取内容到变量中。
在读取了一行后,定义一个std::istringstream
,并将刚刚读取的行内容放入其中。
然后,您可以在一个简单的循环中从这个std::istringstream
中逐个提取单词,并计算每个单词的出现次数。
如果您想看一个示例,请查看下面的代码:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main() {
// 打开一个用于访问文件中数据的流
std::ifstream sourceFileStream("test.txt");
// 检查文件是否能够打开
if (sourceFileStream) {
// 在这里,我们将计算单词的总数
unsigned int totalWords = 0;
// 现在读取文件的每一行
std::string line;
while (std::getline(sourceFileStream, line)) {
// 将行放入一个std::istringstream中,以便我们可以提取单词
std::istringstream iss(line);
// 现在从这个std::istringstream(行)中提取所有单词
std::string word;
while (iss >> word)
++totalWords; // 然后计数
}
std::cout << "\n\n源文件中单词的总数是:" << totalWords << '\n';
}
else std::cerr << "\n\n错误:无法打开源文件\n\n";
}
希望这对您有所帮助。
英文:
You need to read a line by line into a variable using std::getline
in a loop.
After you have read one line, you define a std::istringstream
and put the content of the just read line into it.
Then you can extract word by word from this std::istringstream
in a simple loop and count each occurrence of a word.
Since you want to see an example, please check the below:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main() {
// Open a stream for accessing data in the file
std::ifstream sourceFileStream("test.txt");
// Check, if the file could be opened
if (sourceFileStream) {
// Here we will count the total number of word
unsigned int totalWords = 0;
// Now read each line of the file
std::string line;
while (std::getline(sourceFileStream, line)) {
// Put the line into a std::istringstream, so that we can extract words
std::istringstream iss(line);
// And now extract all words from this istringstream (line)
std::string word;
while (iss >> word)
++totalWords; // and, count
}
std::cout << "\n\nThe toal number of words in the source file is: " << totalWords << '\n';
}
else std::cerr << "\n\nError: Source file could not be opened\n\n";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论