数组中的std :: cin

1 c++

我是一名CS学生,试图掌握一些C++基本概念.我试图从std :: cin获取用户的输入并将其放入数组.

例如:

输入> ab ba cd [按下Entey键]然后我希望数组包含[ab] [ba] [cd].

到目前为止,我有:

#include <iostream>
#include <string>

int main(int argc, char** argv)
{
    std::cout << "Please give all strings seperated with white space (eg. ab ba cd) : ";
    std::string input[12];
    int i=0;

    while(std::cin >> input[i])
    {
        if(input[i].compare("\n")) break;
        i++;
    }
    //This will print contents of input[].
    for(int k = 0 ; k < 12 ; k++)
    {
        std::cout << "input[" << k << "] = " << input[k] << std::endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但遗憾的是,这只将第一个字符串(在本例中为"ab")存储在数组的第一个索引中.

如果我注释掉if(input [i] .compare("\n"))中断; 将产生分段错误.我猜是因为我超出了为数组分配的内存并写入了一个我不应该的地方.

据我所知,到目前为止std :: cin将首先将ab放在数组的input [0]中,并在流中保留剩余的字符串[ba cd],然后在下一个循环中(在i ++之后)[ba cd]将仍然在流中,cin将不会从键盘进一步读取(因为某些内容在流上)并且它应该将字符串ba放在输入[1]等等.如果我错了,请纠正我.

注意:这不是作业.我的课程开始于大约1个月.任何帮助非常感谢.提前致谢

Tim*_*Tim 6

std :: string :: compare不返回布尔值 - 它返回一个int.这用于排序字符串.如果左侧字符串较小,则返回<0;如果右侧字符串较小,则返回> 0;如果相同,则返回0.0与boolean false相同,所以只要字符串不是"\n",你的if语句就会中断 - 这就是你在第一次迭代时突破循环的原因.

此外,cin不会给你换行符 - 所以检查"\n"将不起作用.使用getline将在这里帮助您.

此页面对于使用cin/cout,istream/ostream,istringstream/ostringstream非常有用:http://www.cplusplus.com/reference/iostream/istream/

我把它保存在我的书签中,并定期使用它.

所以,这可能是你想要做的:

#include <sstream>
std::string line;
getline(std::cin, line);  // get the entire line

// parse each string from the line
std::istringstream stream(line);
for (int i=0; stream.good(); i++) {
  stream >> input[i];
}
Run Code Online (Sandbox Code Playgroud)

请注意,您还应该尝试允许超过12个输入字符串而不会崩溃,这可以通过向量来完成:

// parse each string from the line
std::vector< std::string > input;
std::istringstream stream(line);
while (stream.good())
{
  std::string temp;
  stream >> temp;
  input.push_back(temp);
}
Run Code Online (Sandbox Code Playgroud)

向您添加新字符串时,向量将动态增长.从某种意义上说,它有点像一个"更聪明"的阵列 - 你不需要在开始时就知道它的全尺寸.你可以一次建立一块.