C ++字符串在int时没有连接char,即使它是一个char

时间:2015-03-27 22:37:18

标签: 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

        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

这非常令人沮丧;请帮助解释为什么它不起作用或评论它对你有用。

1 个答案:

答案 0 :(得分:2)

似乎只有在他们之后有空格时才会打印单词:

if (ch == ' ') {
    ....
        cout << "\x1b[34;1mWORD: " << word << "\x1b[0m" << end;
    ....
}

给定测试中的数字不是这种情况。