繁体   English   中英

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

[英]C++11 - Program cuts off first letter of every input [Using: cin.ignore and getline)

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

#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;
}

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

2 inches
4 inches
aldosta, Georgia
iami, Florida

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

- 谢谢!

删除对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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM