为什么执行结果中会出现空格?

时间:2018-07-29 00:48:11

标签: c++

这是我的代码:

#include <iostream>
using namespace std;

int main(){
    char *data = new char[20];
    for(int i = 0; i < 2; i++){
        cin >> (data+i*10);
    }
    for(int i = 0; i < 20; i++){
        if(*(data+i) == '\n'){
            cout << " newline ";
        }else{
            cout << *(data+i);
        }
    }
    int test = static_cast<int>(*(data+9));
    cout << "this is a test " <<  test;
    system("pause");
    return 0;
}

我的输入是这样的:

123456789
123456789

执行是这样的:

123456789
123456789
123456789 123456789 this is a test 0 . . .

变量test为0。ASCII空格为十进制32。

为什么我的执行结果中有两个空格(第一个9和1之间的空格,第二个9和t之间的空格)?

1 个答案:

答案 0 :(得分:3)

不是空格字符。它们是不可打印的字符try: loop.run_until_complete(main_loop(tasty_client, streamer)) except KeyboardInterrupt: print("Received exit, exiting") # find all futures/tasks still running and wait for them to finish pending_tasks = [ task for task in asyncio.Task.all_tasks() if not task.done() ] loop.run_until_complete(asyncio.gather(*pending_tasks)) loop.close() exit()#stops the script

请注意,cppreference表示函数std::operator>>(std::istream&, char*)(该页面上的函数#2):

  

不提取空格字符。

  

附加的空字符值'\0'存储在输出的末尾。

因此,当CharT()在您的输入中遇到换行符时,它将空字符写入operator>>data[9]。打印出来的效果取决于您的终端。显然,您的设计使它看起来像一个空间。

但是请注意,提取到data[19]中的此函数非常危险,因为它可能会超出有效存储空间的范围。特别是,请不要在真实代码中将此功能与char*一起使用,因为您不能阻止用户输入超出您分配的范围的输入。而是创建一个std::cin并输入其中,该字符串将根据需要自动增长字符串。

相关问题