gpt4 book ai didi

c++ - 在C++中读取带空格的字符串

转载 作者:可可西里 更新时间:2023-11-01 18:17:16 34 4
gpt4 key购买 nike

如何读取带有空格的输入行(字符串类型)?我试过 getline 但它进入了无限循环。以下是我的代码。

#include <iostream>
#include <cstring>

#define MAX 50 //size of array

//Used G++ 4.6.3 compiler
using namespace std;

int main() {

struct Manager {
string name;
int age;
int working_years;
string phone;
int salary;
}info[MAX];

char inp; //To choose options
int array_pos = 0; //Current position in array of Manager structure
string search_name; //Manager name you want to search

cout << "Press 'i' to insert manager information or 's' to search for manager information by name or 'a' to abort: ";
cin >> inp;

while(inp != 'a') {
int search_num = 0; //array position at which search result is found
int found = 0;
if (inp == 'i' || inp == 's') {
if (inp == 'i') {
int k = array_pos;
cout << "Enter the information of the manager no "<<k+1<<" is : ";

cout << "Enter the Name : ";
//infinte loop occurs
getline(info[array_pos].name, '\n');
//cin >> info[array_pos].name;

cout<<"Enter manager age : ";
cin >> info[array_pos].age;

cout << "Enter manage working years : ";
cin >> info[array_pos].working_years;

cout << "Enter manager phone no. : ";
cin >> info[array_pos].phone;

cout << "Enter manager salary : ";
cin >> info[array_pos].salary;
array_pos++;
}
if (inp == 's') {
cout << "Enter the manager name you want to search : ";
cin >> search_name;
for(int i = 0; i < array_pos; i++) {
//using str1.compare(str2) to compare manager name
if(info[i].name.compare(search_name) == 0) { //manager name found in array of structure
found = 1;
search_num = i;
cout << "Name : " << info[search_num].name << "\n";
cout << "Age: " << info[search_num].age << "\n";
cout << "Working Years: " << info[search_num].working_years << "\n";
cout << "Phone No. : " << info[search_num].phone << "\n";
cout << "Salary : " << info[search_num].salary << "\n";
} //end of if loop for comparing string
} //end of for loop for searching
if(found == 0)
cout << "No Manager by this name exist in record" << "\n";

} //end of if loop

} //end of if loop for searching or insertion
if(inp == 'a')
break;

cout << "Press 'i' to insert manager information or 's' to search for manager information by name or 'a' to abort: ";
cin >> inp;
} //end of while loop

return 0;
}

最佳答案

How can I read input line(type string) with whitespace?

std::string line;
if (std::getline(std::cin, line)) {
...
}

请注意,除了检查 std:getline 调用的返回值外,您还应避免将 >>> 运算符与 std::getline 混合使用> 通话。一旦决定逐行读取文件,在使用字符串流对象的同时进行一个巨大的循环并进行额外的解析似乎更清晰、更合理,例如:

std::string line;
while (std::getline(std::cin, line)) {
if (line.empty()) continue;
std::istringstream is(line);
if (is >> ...) {
...
}
...
}

关于c++ - 在C++中读取带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476668/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com