C++ C++;字符串在int时不连接字符,即使它是字符

C++ C++;字符串在int时不连接字符,即使它是字符,c++,string,file,parsing,io,C++,String,File,Parsing,Io,以下是我的可运行代码: #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 strin

以下是我的可运行代码:

#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;
}
然后在
g++test.cpp
-如果您命名文件
test.cpp
-和
/a.out test
-如果您将上述测试文件存储到
test
-您将看到(令人沮丧的是)
单词:…
(蓝色)如果数字是单个字符,则从不包含数字

例如,我的
输出

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;
    ....
}
if(ch==''){
....

提示:这是针对linux的;在Windows上可能会有很多恼人的纯文本ANSI转义序列。那么输出应该是什么呢?即使一个单词只是一个表示int的字符(
'1'
'3'
,等等),它仍然应该在
单词:
之后打印(因为它仍然是一个单词);但是,事实并非如此,例如,您的输入是line2424523523,并且它在“line”之后停止?您仅在看到空格时打印单词。但行尾没有空格。
if (ch == ' ') {
    ....
        cout << "\x1b[34;1mWORD: " << word << "\x1b[0m" << end;
    ....
}