std::cin input with spaces?

2018-12-31 01:51发布

#include <string>

std::string input;
std::cin >> input;

The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?

I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:

struct cd
{
    std::string CDTitle[50];
    std::string Artist[50];
    int number_of_songs[50];
};

std::cin.getline(library.number_of_songs[libNumber], 250);

This yields an error. Any ideas?

标签: c++ string space
7条回答
一个人的天荒地老
2楼-- · 2018-12-31 02:13

You want to use the .getline function in cin.

#include <iostream>
using namespace std;

int main () {
  char name[256], title[256];

  cout << "Enter your name: ";
  cin.getline (name,256);

  cout << "Enter your favourite movie: ";
  cin.getline (title,256);

  cout << name << "'s favourite movie is " << title;

  return 0;
}

Took the example from here. Check it out for more info and examples.

查看更多
只靠听说
3楼-- · 2018-12-31 02:13

THE C WAY

You can use gets function found in cstdio(stdio.h in c):

#include<cstdio>
int main(){

char name[256];
gets(name); // for input
puts(name);// for printing 
}

THE C++ WAY

gets is removed in c++11.

[Recommended]:You can use getline(cin,name) which is in string.h or cin.getline(name,256) which is in iostream itself.

#include<iostream>
#include<string>
using namespace std;
int main(){

char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
查看更多
泪湿衣
4楼-- · 2018-12-31 02:16

You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));
查看更多
美炸的是我
5楼-- · 2018-12-31 02:16

Use :

getline(cin, input);

the function can be found in

#include <string>
查看更多
牵手、夕阳
6楼-- · 2018-12-31 02:24

It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".

Use std::getline:

int main()
{
   std::string name, title;

   std::cout << "Enter your name: ";
   std::getline(std::cin, name);

   std::cout << "Enter your favourite movie: ";
   std::getline(std::cin, title);

   std::cout << name << "'s favourite movie is " << title;
}

Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.

Update

Your edited question bears little resemblance to the original.

You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.

查看更多
看风景的人
7楼-- · 2018-12-31 02:24

This is an old question but can someone tell me if my solution is incorrect:

std::string s, temp;
std::stringstream ss;
while(std::cin>>temp){
    ss<<temp;
    ss<<" ";
}
s = ss.str();
查看更多
登录 后发表回答