【发布时间】:2021-03-02 05:26:24
【问题描述】:
编写并测试一个程序,提示用户输入文件名和要测试的字符串。在文件中搜索指定字符串的每次出现——找到字符串后,显示包含它的行。找到所有出现的字符串后,显示该字符串在文件中出现的次数。提示:你可以使用字符串成员函数 find()。
这是我的代码,正如我所说,它适用于一些句子但不是全部,它似乎与长度没有任何关系,就像我重复我知道有效的一行一样,它不会遇到任何错误,谁能解释一下?
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
void find_common_words(string, int);
vector<string> words;
int main(){
vector<string> line;
string input;
char filename[50];
ifstream inputFile;
cout << "Enter File Name:" << endl;
cin.getline(filename, 50);
inputFile.open(filename);
//TESTING IF FILE IS OPEN
if (!inputFile.is_open()){
cout << "File Wasn't Opened!" << endl;
return 0;
}
while (getline(inputFile, input)){
line.push_back(input);
}
int size_of_array = static_cast<int>(line.size());
for (int i = 0; i < size_of_array; i++){
istringstream iss(line[i]);
int word_number = 0;
do {
string word;
iss >> word;
words.push_back(word);
word_number++;
} while (iss);
}
string commonword;
cout << "Enter a word to search for (without punctuation)" << endl;
cin >> commonword;
int size_of_array2 = static_cast<int>(words.size());
find_common_words(commonword, size_of_array2);
return 0;
}
void find_common_words(string search, int sizeofarray2) {
//CONVERSION TO STRING WITHOUT PUNCTUATION
for (int i = 0; i < sizeofarray2; i++){
string temp_string = words[i];
for (int j = 0, len = temp_string.size(); j < len; j++){
if (ispunct(temp_string[j])){
temp_string.erase(j--, 1);
len = temp_string.size();
}
}
words[i] = temp_string;
}
//SEARCHING FOR SAME WORDS
int line_number = 1;
int words_found = 0;
for (int i = 0; i < sizeofarray2; i++){
if (search == words[i]){
cout << search << " Was found on line " << line_number << endl;
words_found++;
}
if (words[i].length() == 0){
line_number++;
}
}
cout << line_number - 1 << " lines checked, " << words_found << " matches " << endl;
}
这是我的输入文件(随机生成):
It's a very big deal.
Carl won the spelling bee and got a trophy!
Why is your cat so big?
Do you have a big bowl I can borrow?
It's a big company.
Penguins live in the Antarctica.
Don’t be silly, you're going to the game!
What are you talking about?
He threw up in the trash can!
You're so ratchet!
But she is a good caretaker.
Tom is looking for a bigger house to live in.
调试断言出现错误 表达式 c> = -1 && c
【问题讨论】:
-
使用GCC 作为
g++ -Wall -Wextra -g调用编译您的代码,然后使用valgrind 和GDB 来了解您的可执行文件的行为。如果允许,请考虑在您的笔记本电脑上安装Debian。另请参阅this C++ reference 了解每个 函数、class、您正在使用但未定义的类型或运算符 -
我真的很好奇当你把这个
if (ispunct(temp_string[j]))替换成这个if (std::ispunct(static_cast<unsigned char>(temp_string[j])))时会发生什么 -
@BasileStarynkevitch 对于新手来说这是一个很好的评论。向刚开始学习编写 C++ 代码的人推荐 valgrind 和 gdb 是一个非常好的主意。我总是很高兴看到这么好的cmets。谢谢你,+1
-
@WhozCraig 它实际上看起来解决了问题。
-
我猜你的输入中有一个非 ascii 字符,直接向
ispunct支付一个字符仅适用于 ascii 字符,请参阅en.cppreference.com/w/cpp/string/byte/ispunct