c++ - 按下回车键时停止将值输入数组

标签 c++ arrays

大家好,我在尝试实现程序的回车键部分时遇到了问题

int list[50];
int i = 0;
while (/*enter key has not been pressed*/&& i < 50){
  cin>>list[i];
  i++;
  }

它的工作原理是,它将接受以空格分隔的整数并将它们存储到数组中。当按下回车键时,它应该停止接受输入。

PS 我是通过手机发布的,这就是我无法正确设置文本格式的原因。如果语法有任何问题,它可能只是被忽略设置,因为我只关心“输入键”部分。

最佳答案

您可以使用字符串流,基本上是将整行读入一个字符串,然后开始将该字符串中的整数读入您的数组。
当您按下 Enter 时,读取字符串将终止,所以我认为这对您有用

#include <iostream>
#include <string>
#include <sstream>

using namespace :: std; // bad idea, I am just lazy to type "std" so much
int main (){


    const int arrSize = 5;

    int arr [arrSize] = {0}; //initialize arr zeros
    string line;
    getline(cin,line);


    cout <<"you entered " << line<<endl; // just to check the string you entered
    stringstream ss (line);

    int i = 0;
    while ( ss>>arr[i++] && i < arrSize); // this might look a bit ugly


    for (int i =0; i < arrSize; i++) // checking the content of the list
        cout<<arr[i]<<" ";

    getchar();


    return 0;



}

请注意,它不会测试用户的错误输入(例如字母而不是数字)。

关于c++ - 按下回车键时停止将值输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22721465/

相关文章:

c++ - 在标准类型上使用原子操作

arrays - 算法帮助 : how to divide array into N segments with least possible largest segment (balanced segmenting)

java - 愚蠢的 For 循环实现

arrays - 与数组相同的 'degree' 子数组的个数

java - 交换数组的两个部分的位置

python - 动态向数组添加新行

c++ - 如何在此 C++ 程序中创建搜索函数

c++ - 立即终止线程

c++ - 升级到 Xcode 8 后 GCC 5.4 链接器错误

c++ - 我会因单例过度而感到过度杀伤力吗?