我正在尝试编写一个程序来读取文本文件,计算每个唯一单词,然后对唯一单词列表进行排序并列出每个单词的出现次数。但是,我似乎无法在不弄乱和读取字母、数字和符号的情况下从字符串中读取单个单词。我读过其他主题,但我的逻辑在某些方面存在严重缺陷,我看不到。
int main()
{
fstream fp;
string line;
fp.open("syllabus.txt", ios::in);
getline(fp, line);
string word = findWords(line);
cout << word << endl;
}
string findWords(string &line)
{
int j = 0;
string word;
for(int i = 0; i < line.size(); i++)
{
while(isalpha((unsigned char)line[j]) != 0 && isdigit((unsigned char)line[j]) != 1)
j++;
word += line.substr(0, j) + " + ";
line = line.substr(j, (line.size() - j));
}
return word;
}
最佳答案
您的代码块有很多问题。对于一个人,您不想在遍历它时更改行。通常,您不应该更改迭代的内容。您需要一个开始索引和一个结束索引(从搜索中找到)。
这里有一个技巧,你可以用 >> 运算符读取一个单词
ifstream fp( "syllabus.txt" );
string word;
vector<string> words;
while (fp>> word)
words.push_back(word);
关于c++ - 从字符串 C++ 中读取单词,同时忽略空格、数字和符号。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943385/