从同一文件中读取字符串和Ints

时间:2013-02-27 03:15:00

标签: c++ string

的形式提供输入
fifteen,7,fourth-four,2,1,six
66,eight-six,99,eighteen
6,5,4,3,2,1

我可以使用什么来将其读成我可以解析的格式?目标是能够对数字进行排序,然后按顺序将它们打印出来,格式与我们给出的格式相同。例如,以下内容应打印为

    1,2,six,7,fifteen,forty-four
    eighteen,66,eighty-six,99
    1,2,3,4,5,6

我知道应该如何进行排序,我只是在确定读取输入的最佳方法时遇到了麻烦。目前,我正在使用这样做:

#include <iostream>
#include <string>
using namespace std;

int main() {
    char word;
    char arr[20];

    int count = 0;

    while (cin >> word) {
        if (word == '\n') {
            cout << "Newline detected.";
        }
        cout << "Character at: " << count << " is " << word << endl;
        count++;
    }
}

这不起作用,因为从来没有\n读入。

1 个答案:

答案 0 :(得分:2)

IMO最简单的方法是使用std :: istream的getline函数,并使用','作为分隔符。

E.g。像。的东西。

char dummystr[256];
int count = 0;
while (cin.getline(dummystr, 256, ',')) {
    cout << "Character at: " << count << " is " << dummystr << endl;
    ++count;
}

对于每行都有逗号分隔符的换行符分隔符(你真的应该选择一个):

char dummystr[256]; // not max size for the string
int count = 0;
while (cin.getline(dummystr, 256, '\n')) {
    std::stringstream nested(dummystr);
    char dummystr2[256];
    while (nexted.getline(dummystr2, 256, ',')) {
        cout << "Character at: " << count << " is " << dummystr << endl;
        ++count;
    }
}
相关问题