【问题标题】:How can I create a auto-incrementing array in a C++ while loop?如何在 C++ while 循环中创建自动递增数组?
【发布时间】:2012-10-22 04:45:28
【问题描述】:

我有一个使用 stringstream/getline() 来解析字符串的 while 循环,但是我在处理循环中的结果时遇到了麻烦。循环将字符串分成 3 部分,并将每个单词放入该循环循环的变量“word”中。但是,我怎样才能将每个部分存储在一个变量或数组中,以便我可以在 while 循环之外使用它?

循环

string word;
    stringstream stream(cmdArgs.c_str());
    while( getline(stream, word, ' ') )
          // Manipulate results

变量“cmdArgs”是字符串。

【问题讨论】:

  • 只是提到boost::split() 可以为您填充std::vector<std::string>

标签: c++ arrays string while-loop


【解决方案1】:

使用向量可以将字符串分解为单词并单独存储每个单词,无论有多少:

string word;  
stringstream stream(cmdArgs.c_str());  
vector<string> words;  
while( getline(stream, word, ' ') )  
{  
    words.push_back(word);  
}  

如果你确信正好有 3 个单词,你也可以只使用一个普通数组:

string word;  
stringstream stream(cmdArgs.c_str());  
string words[3];  
int index = 0;  
while( getline(stream, word, ' ') )  
{  
    words[index++] = word;  
}  

但是如果传入的字符串比你预期的长,你会溢出该数组。

【讨论】:

    【解决方案2】:
    string word;
    vector<string> words;
    stringstream stream(cmdArgs.c_str());
    while( getline(stream, word, ' ') )
    {
        words.push_back(words);
    }
    // Manipulate results
    

    查看矢量类:http://www.cplusplus.com/reference/stl/vector/

    【讨论】:

    • 另见 std::deque 和 std::list
    猜你喜欢
    • 2019-05-09
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2020-11-27
    相关资源
    最近更新 更多