Why are some strings cutoff when attempting to read a mixture of numeric and non-numeric input as in the following code?

☆樱花仙子☆ 提交于 2019-12-11 01:57:26

问题


Program:

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main(){
    double x;
    string name;
    while(cin >> name){
        cout<<name<<endl;
        while (cin >> x);
        cin.clear();
    }
}

Input:

Moo 100 100 100 100 100 100 100 100
Moore 75 85 77 59 0 85 75 89
Norman 57 78 73 66 78 70 88 89
Westerly 43 98 96 79 100 82 97 96
Edwards 77 72 73 80 90 93 75 90
Franklin 47 70 82 73 50 87 73 71
Jones 77 82 83 50 10 88 65 80
Carpenter 47 90 92 73 100 87 93 91

Output:

Moo
Moore
orman
Westerly
wards
ranklin
Jones
rpenter

I started working through the book accelerated C++ and ran into a piece of the authors code (chapter 4) that was not working as expected on my machine (the above sample is abbreviated but experiences the same problem as the code directly from the book). The intent is to print all the names from the beginning of the lines of numbers representing student grades in the input. What actually happens is that some of the names are printed in full while others, apparently at random, have letters missing from the start. I was hoping someone here could shed some light on why this is happening.

My initial thought was that in the process of failing on reaching non-numeric input the line:

 while (cin >> x);

was somehow overshooting the beginning of the next name but I am having difficulty testing this and I'm unsure of why that should happen.

Update: It seems I was experiencing the same issue as this question with the clang compiler for mac.


回答1:


i can only suspect that the input is done from some file that was prepared by using a text editor that inserts some control symbols in the text. It seems for example that the text editor you used inserts backspace characters in the text.

Use a text editor that does not insert any control symbols in text.



来源:https://stackoverflow.com/questions/24640314/why-are-some-strings-cutoff-when-attempting-to-read-a-mixture-of-numeric-and-non

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!