C++ 告诉 cin 在换行符处停止阅读

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9673708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:09:40  来源:igfitidea点击:

tell cin to stop reading at newline

c++

提问by Mark

Suppose I want to read line a of integers from input like this:

假设我想从输入中读取整数 a 行,如下所示:

1 2 3 4 5\n

I want cin to stop at '\n' character but cin doesn't seem to recognize it.

我希望 cin 停在 '\n' 字符处,但 cin 似乎无法识别它。

Below is what I used.

下面是我用的。

vector<int> getclause() {
  char c;
  vector<int> cl;

  while ( cin >> c && c!='\n') {    
    cl.push_back(c);
    cin>>c;
  }
  return cl;
}

How should I modify this so that cin stop when it see the '\n' character?

我应该如何修改它,以便 cin 在看到 '\n' 字符时停止?

回答by mfontanini

Use getline and istringstream:

使用 getline 和 istringstream:

#include <sstream>
/*....*/
vector<int> getclause() {
  char c;
  vector<int> cl;
  std::string line;
  std::getline(cin, line);
  std::istringstream iss(line);
  while ( iss >> c) {    
    cl.push_back(c);
  }
  return cl;
}

回答by Geoffroy

You can use the getlinemethod to first get the line, then use istringstreamto get formatted input from the line.

您可以使用getline方法首先获取该行,然后使用istringstream从该行获取格式化的输入。

回答by piokuc

Use std::getline, this will do the trick

使用 std::getline,这会解决问题

回答by subtleseeker

From this link, it is quite simple to achieve this.

从这个链接,实现这一点非常简单。

#include <stdio.h>
int main(void) {
    int i=0,size,arr[10000];
    char temp; 
    do{
        scanf("%d%c", &arr[i], &temp); 
        i++; 
        } while(temp!= '\n');

    size=i; 
    for(i=0;i<size;i++){ 
        printf("%d ",arr[i]); 
    } 
    return 0;
}