为什么cout()切掉多个字符?

时间:2018-06-21 14:17:50

标签: c++

#include <iostream>
#include <vector>

using std::cin; using std::cout; using std::istream;
using std::vector; using std::endl;

struct Student_info {
    std::string name;
    double midterm;
    double final;
    std::vector<double> homework;
};

istream& read_hw(istream& in, vector<double>& hw)
{
    if (in) {
        hw.clear();
        double x;
        while (in >> x) {
            cout << "double Grade from read_hw(): " <<  x << "\n";
            hw.push_back(x);
        }
        in.clear();
        }
    return in;
}

istream& read(istream& is, Student_info& s)
{
    is >> s.name >> s.midterm >> s.final;
    std::cout << "string Name from read()" << s.name << std::endl;
    read_hw(is, s.homework);  // read and store all the student's homework grades
    return is;
}

int main() {
  Student_info s;
  vector<double> hw;
  while (read(cin, s)) {
    cout << "String name from main()" << s.name << endl;
  }
}

示例输入/输出: (我输入了Jimbo 99 99 99 99,它会按预期打印。然后我输入了Failure 5 5 5 5 5,结果如下所示。)

String name from main()Jimbo
string Name from read()lure
double Grade from read_hw(): 5
double Grade from read_hw(): 5
double Grade from read_hw(): 5
Failure 10 10 10 10 10 // new input.
String name from main()lure
string Name from read()lure
double Grade from read_hw(): 10
double Grade from read_hw(): 10
double Grade from read_hw(): 10
Jimbo 99 99 99 99 99 // new input again. note it prints Jimbo just fine.
String name from main()lure
string Name from read()Jimbo
double Grade from read_hw(): 99
double Grade from read_hw(): 99
double Grade from read_hw(): 99

我已经尝试搜索,但我所得到的只是关于ignore()的东西,我没有使用过。我有一种预感,这与使用while (cin >> x)进行关联,read()接受双打,然后立即切换到下一个SELECT ID, FORMAT(MAX(CONVERT(DATE,STUFF(STUFF(MyDate,3,0,'/'),6,0,'/'))),'MM/dd/yyyy') AS MyDate FROM TableName GROUP BY ID 循环来接收字符串。

1 个答案:

答案 0 :(得分:3)

您之所以会得到这个结果,是因为cin >> x看到字母后会不会失败。在数字和类似数字的实体中允许使用某些字母。顺便说一下,F,A和I(这两种情况都属于其中)(它们出现在infnan字符串中,这些字符串指定特殊的浮点IEEE值)。因此cin >> x将消耗“ Fai”,然后才会失败。

另一方面,J不是这样的字母,因此看到J cin >> x会立即失败,将字母留在流中供下次读取。

缓解策略包括

  • 读取并每行解析一条学生记录
  • 读取令牌并识别它们是否是数字(但是谁说一个人的名字不能是数字?)
  • 在学生记录之间引入明确的分隔符,例如“ |”。
相关问题