这是我的可运行代码:
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char **argv) {
if (argc > 1) { // passed in parameter
ifstream file(argv[1]); // create file from second parameter
string line;
if (file) { // file exists and has been opened
//stack *stmt = new stack();
while (getline(file, line)) { // run through lines of file
string word = "";
cout << "LINE: " << line << endl;
for (int i = 0; i < line.length(); i++) { // run through char of line
char ch = line[i];
if (ch == ' ') {
if (word == "") {
continue;
} else {
//stmt->push(word);
cout << "\x1b[34;1mWORD: " << word << "\x1b[0m" << end;
word = "";
}
} else {
word += ch;
}
}
}
cout << stmt->size() << endl;
while (stmt->has_next()) {
cout << stmt->pop() << endl;
}
} else {
cerr << "\x1b[31;1mNo such file, \x1b[21m" << argv[1] << "\x1b[0m" << endl;
}
} else { // no parameters passed in
cerr << "\x1b[31;1mYou did not specify any files to parse\x1b[0m" << endl;
}
return 0;
}
看起来很简单。但是,当字符 ch
是整数字符(如 '0'
到 '9'
)时,字符就是不附加。
你们有没有遇到过这种情况(如果你像这样创建一个测试文件:
this is from line 1
line 2
3
然后在 g++ test.cpp
之后 - 如果您将文件命名为 test.cpp
- 和 ./a.out test
- 如果您将上面的测试文件存储到 test
- 你会看到(令人沮丧的是)WORD: ...
(蓝色)从不包含一个数字如果数字是单个字符。
即OUTPUT
对我来说:
LINE: this is from line 1
WORD: this
WORD: is
WORD: from
WORD: line
LINE: line 2
WORD: line
LINE: 3
这很令人沮丧;请帮助并解释为什么它不起作用或评论它对你有用。
最佳答案
似乎只有在单词后面有空格时才会打印单词:
if (ch == ' ') {
....
cout << "\x1b[34;1mWORD: " << word << "\x1b[0m" << end;
....
}
给定测试中的数字不是这种情况。
关于C++ 字符串在 int 时不连接 char,即使它是 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311312/