首页 文章

C跳过新的线路键?

提问于
浏览
0

我试图让用户输入一些数据,然后将其存储在一个结构中,但是我知道我应该使用哪个功能以及有什么区别? cin或getline()?我使用的任何一个函数,似乎它接受'\ n'键并使我的程序崩溃,但如果这是问题我不是100%...因为它一直崩溃 .

我和他们两个玩过,这就是我所拥有的 .

string temp;
int id;

cout << endl << "Full name (last, first): ";
cin >> temp;
cin.ignore(1, '\n');
myData[fileSize] = parseName(temp);

cout << endl << "ID: ";
cin >> id;
myData[fileSize].id = id;

cout << endl << "Address: ";
cin >> temp;
temp.copy(myData[fileSize].address, temp.length(), 0);

变量fileSize是数组当前所在的元素,函数parseName将名称拆分为last和first .

我一直在阅读cin.ignore()和noskipws等几个函数,但不知道如何使用它们 . 顺便说一下,用户输入数据的方式是“last,first”,之后是逗号和空格(这是解析函数正在查找的内容) .

另外我不确定地址部分是否是最好的方法,我的结构myData.address是一个字符数组,因为我不知道如何使用字符串 . 我对C仍然没有信心 . 谢谢你的帮助 .

编辑:如果我注释掉ID和地址部分,程序循环自己6次说我有一个无效的条目(这是主要的一部分),所以它按下回车后读取6或7键 . 如果我按照原样保留所有内容,这就是我得到的 .

Full name (last, first): terminate called after throwing an instance of 'std::ou
t_of_range'
  what():  basic_string::copy

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Process returned 3 (0x3)   execution time : 4.328 s
Press any key to continue.

1 回答

相关问题