C ++ 11 - 程序切断每个输入的第一个字母[使用:cin.ignore和getline)

时间:2017-09-20 00:41:35

标签: c++ c++11

美好的一天! 我想知道为什么我的程序(用C ++ 11编写)不断切断每个用户输入的第一个字符。 这是我的代码:

if (item.checked) {
    function valueExist = (element){
        return element.value == gridData[idx].value
    }


    if (!list.find(valueExist) ){
        list.push({
          "Key": gridData[idx].id,
          "Value": gridData[idx].value
        });
    }
  }

如果输入如下,则输出如下: set1 - 12英寸 set2 - 24英寸 set3 - 佐治亚州瓦尔多斯塔 set4 - 佛罗里达州迈阿密

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() {

  ofstream dataFile;
  dataFile.open("studentData.txt");

  string set1, set2, set3, set4;

cout << "How long was the fish when you first measured it?" << endl;
cin.ignore();
getline(cin, set1);
dataFile << set1 << endl;

cout << "How long is the fish now?" << endl;
cin.ignore();
getline(cin, set2);
dataFile << set2 << endl;

cout << "Where was the fish when you first tagged it?" << endl;
cin.ignore();
getline(cin, set3);
dataFile << set3 << endl;

cout << "Where is the fish now?" << endl;
cin.ignore();
getline(cin, set4);
dataFile << set4 << endl;

dataFile.close();

return 0;
}

为什么会这样?我已经阅读了使用cin.ignore和cin.getline,但是,我无法找到合适的解决方案。这是我的语法吗?我不正确地使用这些功能吗? 请记住,我是用C ++编程的初学者! ^^

- 谢谢!

1 个答案:

答案 0 :(得分:0)

删除对cin.ignore()的来电,因为它忽略了您的第一个字符。以下代码对我有用。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

    int main() {

      ofstream dataFile;
      dataFile.open("studentData.txt");

      string set1, set2, set3, set4;

    cout << "How long was the fish when you first measured it?" << endl;
    getline(cin, set1);
    dataFile << set1 << endl;

    cout << "How long is the fish now?" << endl;
    getline(cin, set2);
    dataFile << set2 << endl;

    cout << "Where was the fish when you first tagged it?" << endl;
    getline(cin, set3);
    dataFile << set3 << endl;

    cout << "Where is the fish now?" << endl;
    getline(cin, set4);
    dataFile << set4 << endl;

    dataFile.close();

    return 0;
    }