如何解析字符串并忽略空格?

时间:2017-04-10 04:50:08

标签: c++ string parsing whitespace

int line = 0;
string teststring = " ";
string stringarray[100];

while (codeFile.good())
{
    getline(codeFile, teststring, ' ');

    if(teststring!="" && teststring[0]!='\n' && teststring[0] != 9 && teststring[0] != 10 && teststring[0] != 32 && teststring[0]!=' '
            && teststring!=" " && teststring!="  ")
    {
        stringarray[line]=teststring;        // still stores whitespace :(
        cout << stringarray[line] << endl;
        line++;
    }
}

您好,我正在浏览一个文本文件并尝试将每个字符串存储在数组的元素中,但是存在元素存储完全空白区域的问题。

2 个答案:

答案 0 :(得分:0)

我刚刚解决了类似的问题,这个代码怎么样:

while (codeFile.good())
{
    getline(codeFile, teststring);
    for(size_t idx = 0; idx < teststring.size(); i++) {
        size_t start = idx;
        while (teststring[i] != ' ') {
            idx++;
        }
        stringarray[line] = teststring.substr(start, idx - start);
        cout << stringarray[line] << endl;
        line++;
    }
}

答案 1 :(得分:0)

忽略所有空格正是运算符&gt;&gt;确实

您的代码段可以改写为:

strcat
相关问题