如何在C++中读取带有空格的字符串
How to read in a String with white space in C++
所以我正在为我的 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";
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 移除前面有空格的前2个字符串
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 在 c++ 中逐行阅读字符串,不要以空格停止
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 如何存储包含多个空格的字符串 c++
- 在特定位置为字符串添加空格
- 有没有办法在 c++ 中获取带有空格的完整字符串?
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- Winsock2:当我尝试发送带有空格的字符串时,该函数在遇到空格时似乎停止发送
- 从没有空格的字符串中提取整数
- 用于拆分空格字符串的程序不起作用
- 解析C++中的完整(从头到尾)字符串,包括所有空格
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何获取我的区域设置的空格字符串?