HelloMyWorld__ 2022-11-13 17:59 采纳率: 60%
浏览 25

c++ getchar函数的使用问题

两串代码的目的都是为了把输入的字符串倒叙输出,下面两串代码的差异只在于第一个while循环的循环体,我以为是等效的,但是在分别运行的时候,两串代码的输入方式和输出都不太一样。
对于输入,第一串代码在输入一个字符后必须再按一下回车才能在输入下一个字符,但是第二串代码在输入的时候则不需要,可以直接输进去一个字符串。对于输出,第一串字符在输出数字的时候不是以字符的类型输出,而是按照ASCII码表转换成了别的一些字符,导致输入1-9这些数字,输出的都是空白,而第二串代码则没有这个问题

#include<iostream>
#include<vector>
using namespace std;
int main() {
    vector<char>vec;
    while (1) {
        
        if (getchar() == '\n') {
            break;
        }
        vec.push_back(getchar());
        
    }
    vector<char>::iterator it = vec.end() - 1;
    cout << "开始倒叙输出" << endl;
    while (it != vec.begin()) {
        cout << * it;
        it--;
    }

    cout << *vec.begin();
    return 0;
}

#include<iostream>
#include<vector>
using namespace std;
int main() {
    vector<char>vec;
    while (1) {
        char c = getchar();
        if (c == '\n') {
            break;
        }
        vec.push_back(c);
    }
    vector<char>::iterator it = vec.end() - 1;
    cout << "开始倒叙输出" << endl;
    while (it != vec.begin()) {
        cout << *it;
        it--;
    }

    cout << *vec.begin();
    return 0;
}

我自己测试的输入以及对应的输出:
第一串:

img


第二串:

img

那为什么会出现这种差异呢?求解答

  • 写回答

2条回答 默认 最新

  • xw_lover 2022-11-13 19:14
    关注

    首先,getchar一次只能接收一个字符;其次,getchar在读取结束或者失败的时候,会返回EOF,本质上是-1。你可以看一下这篇文章关于getchar的用法及实例解析_ww here的博客-CSDN博客_getchar的用法,另外对于EOF和ctrl+Z关系关于getchar()读取,EOF和CTRL+Z的一些理解_小豆子范德萨的博客-CSDN博客

    
    #include<iostream>
    #include<vector>
    using namespace std;
    int main() {
        vector<char> vec;
        char ch;
        cout << "请输入:" << endl;
        while ((ch = getchar())!=EOF) {
            vec.push_back(ch);
        }
        vector<char>::iterator it = vec.end() - 1;
        cout << "开始倒叙输出";
        while (it != vec.begin()) {
            cout << *it;
            it--;
        }
        cout << *vec.begin();
        return 0;
    }
    

    其结果是

    img

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 11月13日