공백이있는 std :: cin 입력? 활용할 수 Hello World있습니까? 나는 실제로 구조체로

#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사후에 변환합니다 .


답변

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

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


답변

사용하다 :

getline(cin, input);

이 기능은

#include <string>


답변

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에서 제거되었습니다.

[권장] : 당신은 사용할 수 의 getline (CIN, 이름)string.h
또는 cin.getline (이름, 256)iostream자체.

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


답변

오히려 다음 방법을 사용하여 입력을 얻습니다.

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string name;

    cout << "Hello, Input your name please: ";
    getline(cin, name);

    return 0;
}

공백 문자를 포함하는 문자열에 대해 배열의 총 길이를 정의하는 것보다 실제로 사용하기가 매우 쉽습니다.