C++输入字符串包含 ASCII 26(替换)字符。如何摆脱它?

发布于 2024-09-15 09:35:42 字数 664 浏览 2 评论 0原文

这是我的代码。目的是输入一个学生班级的向量,包含姓名和作业成绩。

istream& input(istream& is, student& s){
    is.clear();
    cout << "Enter student name: ";
    getline(is,s.name);
    grade(is,s.homework);
    return is;
}

istream& grade(istream& is, vector<double>& homework){
    if(is){
        homework.clear();
        double x;
        cout << "Enter grade of student - Ctrl-Z to stop: ";
        while(is>>x)
            homework.push_back(x);
        is.clear();
    }
    return is;
}

问题是第一个学生的名字没问题,但是当程序读取下一个学生的名字(从键盘输入)时,它总是以替换(ASCII 26)字符开头。我猜问题来自输入流,当我使用 CTRL - Z 来表示作业成绩输入结束时。你们能建议一个解决方案吗?

Here's my code. Purpose is to input a Vector of Student class, contain name and homework grades.

istream& input(istream& is, student& s){
    is.clear();
    cout << "Enter student name: ";
    getline(is,s.name);
    grade(is,s.homework);
    return is;
}

istream& grade(istream& is, vector<double>& homework){
    if(is){
        homework.clear();
        double x;
        cout << "Enter grade of student - Ctrl-Z to stop: ";
        while(is>>x)
            homework.push_back(x);
        is.clear();
    }
    return is;
}

The problem is that the first student's name is ok, but when the program read the next student's name (Input from keyboard), it always starts with the substitute (ASCII 26) character. I guess the problem comes from input stream, when I used CTRL - Z to signal the end of the homework grades input. Can you guys suggest a solution ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罪歌 2024-09-22 09:35:42

使用 Ctrl-Z 确实会将 SUB 字符插入到流中。提取到该字符之前的双停止点。因此,您可以使用 istream::ignore() 方法来消除它。使用计数 1 并将 delim 参数设置为 0x1A(SUB 的值)。

is.ignore(1, 0x1A);

另一种可能性是不指示用户键入 Ctrl-Z,只需按 ENTER。

Using Ctrl-Z does insert the SUB character into the stream. Extracting to a double stops just before that character. So you could eliminate it by using the istream::ignore() method. Use a count of 1 and set the delim parameter to 0x1A (the value of SUB).

is.ignore(1, 0x1A);

The other possibility is don't instruct the user to type Ctrl-Z, just press ENTER.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文