Programing

공백이있는 std :: cin 입력?

lottogame 2020. 7. 4. 10:37
반응형

공백이있는 std :: cin 입력?


#include <string>

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

사용자가 "Hello World"를 입력하려고합니다. 그러나 cin두 단어 사이의 공간에서는 실패합니다. 어떻게 cin하면 전체를 활용할 Hello World있습니까?

나는 실제로 구조체로 이것을하고 있는데 cin.getline작동하지 않는 것 같습니다. 내 코드는 다음과 같습니다.

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

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

오류가 발생합니다. 어떤 아이디어?


당신은 사용해야합니다 cin.getline():

char input[100];
cin.getline(input,sizeof(input));

"실패"하지 않습니다. 그냥 읽지 않습니다. 어휘 토큰을 "문자열"로 간주합니다.

사용 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;
}

이 것을 참고 하지 와 같은 std::istream::getlineC 스타일로 작동 char버퍼가 아니라 std::string의.

최신 정보

편집 한 질문은 원본과 거의 유사하지 않습니다.

문자열이나 문자 버퍼가 아닌 getline들어 가려고했습니다 int. 스트림의 형식화 작업은 operator<<로만 작동 operator>>합니다. 그중 하나를 사용하고 (다중 단어 입력에 따라 적절히 조정), 사용 getline하고 어휘 적으로 int사후에 변환합니다 .


사용하다 :

getline(cin, input);

이 기능은

#include <string>

표준 라이브러리는 ws입력 스트림에서 공백을 사용하는 입력 함수를 제공 합니다. 다음과 같이 사용할 수 있습니다.

std::string s;
std::getline(std::cin >> std::ws, s);

cin에서 .getline 함수를 사용하려고합니다.

#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;
}

여기 에서 예를 들었습니다 . 자세한 정보와 예제를 확인하십시오.


C 웨이

getscstdio (stdio.h in c)에있는 함수 를 사용할 수 있습니다 .

#include<cstdio>
int main(){

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

C ++ 방법

gets 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
}

참고URL : https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces

반응형