我有这个简单的 C++ 程序;
#include <iostream>
using std::endl;
using std::cout;
using std::cin;
using std::getline;
#include <string>
using std::string;
struct Repository
{
string name;
string path;
string type;
string command;
};
int main()
{
Repository rp;
cout << "\nEnter repo name: ";
cin >> rp.name;
cout << "Enter repo path: ";
cin >> rp.path;
cout << "Enter repo type: ";
cin >> rp.type;
cout << "Enter repo command: ";
getline(cin, rp.command);
cout << "\nRepository information: " << endl;
cout << rp.name << "\n" << rp.path << "\n" << rp.type << "\n" << rp.command << endl;
return 0;
}
当程序执行到"getline(cin, rp.command)"时,程序只是打印出"输入repo命令:",然后跳过了"getline(cin, rp.command)"这一行,导致用户没有时间回答。可能的问题是什么?当执行到 "getline(cin, rp.command)" 时,程序会等待用户输入命令并按下回车键。如果该行被跳过,可能是由于之前的输入操作已经留下换行符,使得 getline() 函数读取到了一个空行。解决方法可以在输入操作前使用 cin.ignore() 来清除之前留下的换行符。
rp.command
保持为空? - ST3#include <iostream>
并在开头清除缓冲区。 - MarmiK