如何在C++中读取带有空格的字符串

How to read in a String with white space in C++

本文关键字:空格 字符串 读取 C++      更新时间:2023-10-16

所以我正在为我的 CS175 C++课程做一个家庭作业问题。我们有一个家庭作业,我们必须做一顶短帽,有点像哈利波特中的帽子。我已经完成了 99% 的代码,但是让我感到困惑的是如何在带有空格的字符串中读取。

我们需要能够输入全名,所以很明显,仅仅使用 std::cin>>是行不通的。问题是我似乎无法获得迄今为止尝试过的任何方法。

这是我的代码:

#include <iostream>
#include <string>
int main()
{
int NumStudents;
std::string NameStudents;
int StartValue;
int House;
std::string HouseName;
int NumCornfolk = 0;
int NumEsophagus = 0;
int NumBob = 0;

//How many students are there?
std::cout << "How many students are there? n";
std::cin >> NumStudents;

for (StartValue = 0; StartValue < NumStudents; StartValue++) {
std::cout << "Please enter the name of the next student. n";
std::cin >> NameStudents; \**THE PROBLEM IS HERE**
//Assings the House
House = rand() % 100 + 1;
if (House <= 19) {
HouseName = "Cornfolk! n";
NumCornfolk++;
}
else if (House > 19 && House < 50) {
HouseName = "Esophagus! n";
NumEsophagus++;
}
else if (House >= 50) {
HouseName = "Bob! n";
NumBob++;
}
std::cout << NameStudents << " got " << HouseName << std::endl;

}
//Prints Results
std::cout << "Number of Students in each House: n";
std::cout << "Cornfolk:" << NumCornfolk << " Esophagus:" << NumEsophagus << " Bob:" << NumBob;
}

读取 std::cin 的代码行>> NameStudents; 是导致问题的原因。我见过一些方法说使用类似"std::cin.getline (name,256("的东西,但是cin.getline在句点抛出错误并且无法编译。

能够正确读取名称只有 2/11 分,所以没什么大不了的,但我想知道为什么建议的方法在这里不起作用。

谢谢。这个问题与模组之前提出的问题不同。

使用std::getline,像这样:

std::getline(std::cin, NameStudents);

以下是 https://en.cppreference.com/w/cpp/string/basic_string/getline 中的示例:

std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.n";