简体   繁体   English

getline() 和字符数组

[英]getline() and char array

I am so sorry, I know this is a basic problem, but I couldn't find an answer anywhere.很抱歉,我知道这是一个基本问题,但我在任何地方都找不到答案。 Maybe I didn't realize the key word.也许我没有意识到关键词。 The problem is:问题是:

I want to get inputs from user, which will be stored in the check[] array, then I see through it to get if inputs are valid or invalid (valid if it is like SpaceSpace+0000[i=1-5] ).我想从用户那里获取输入,这些输入将存储在check[]数组中,然后我通过它查看输入是有效还是无效(如果它像SpaceSpace+0000[i=1-5] )。

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cmath>
    #include <iomanip>
    #include <string>
    #include <cstring>    
    void main(){
    char check[7];
        for(i=0;i<7;i++){
                    check[i]='1';
            };
        //int check[4];
        cin.getline(check,4);
          bool cond=1;
            for(i=0;i<7;i++){
                    cout<<check[i];
            };
          }

But when I print ( cout ) the array, I realized this: Input is 33 , array[] is " 33 ' Space '1111" , my question here is what does the space in output mean and how could I deal with it(ignore, remove or anything).但是当我打印( cout )数组时,我意识到这一点: Input is 33 , array[] is " 33 ' Space '1111" ,我的问题是输出中的空格是什么意思,我该如何处理它(忽略,删除或任何东西)。

The problem is that istream::getline reads the input, and then write a null-terminated byte string to your array.问题是istream::getline读取输入,然后将空终止字节字符串写入数组。

What you see as a "space" is simply the null-terminator '\\0' .您看到的“空格”只是空终止符'\\0'

If you want to read raw unformated characters, use a loop to read one character at a time instead (checking for eof and newline):如果您想读取未格式化的原始字符,请使用循环一次读取一个字符(检查eof和换行符):

char ch;

// Read up to four character, or until there's an error or end-of-file,
// or until you get a newline
for (unsigned i = 0; i < 4 && cin.get(ch) && ch != '\n'; ++i)
{
    check[i] = ch;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM