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

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

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

最佳答案

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

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

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

关于C++ 字符串在 int 时不连接 char,即使它是 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311312/

相关文章:

c++ - Linux系统调用+交叉编译

c++ - 如何使用数组按引用对对象进行排序? (以一种不那么愚蠢/复杂的方式。)

javascript - Javascript 中的通配符字符串比较

计算关键字与短文本(50 - 100 字)相关性的算法

python - 如何从一个文件中获取在另一个文件中包含字符串的所有行?

c++ - fread/fwrite 大小和计数

c++ - 使用 'unsigned int' 读取 'cin'

c++ - 我应该在这里使用删除删除惯用语吗?

java - 字符串中重复次数最多的字符

file - Windows 2008 R2 - 内核(系统进程 PID=4)正在锁定文件和文件夹