空格后的字符未打印出来

问题描述

我使用字符数组从用户获取输入,然后显示输出。但是,每次输入带有空格的值时,仅会打印出空格前的第一个单词。

例如,这是我键入的内容

Customer No.: 7877 323 2332

这将是输出

Customer No.: 7877

我已经在寻找可能的解决方案,但似乎找不到正确的解决方案。

这是我的参考代码

#include<iostream>
using namespace std;

int main()
{
    char custNum[10] = " ";  // The assignment does not allow std::string
    
    cout << "Please enter values for the following: " << endl;
    cout << "Customer No.: ";
    cin >> custNum;
    
    cout << "Customer No.: " << custNum << endl;
}

解决方法

另一种选择是使用std::basic_istream::getline将整个字符串读入缓冲区,然后通过简单的for循环删除空格。但是,当使用普通字符数组时,不要忽略缓冲区大小。太长的1000个字符比太短的1个字符要好得多。输入时,custNum的绝对最小大小为14个字符(显示的13加上'\0'(以零结尾)的字符。(粗略的经验法则,请采用您估计的最长输入并将其加倍-以便允许用户犯错误,踩键盘等操作...)

在这种情况下,您可以简单地执行以下操作:

#include <iostream>
#include <cctype>

int main() {
    
    char custNum[32] = " ";  // The assignment does not allow std::string
    int wrt = 0;
    
    std::cout << "Please enter values for the following:\nCustomer No.: ";
    
    if (std::cin.getline(custNum,32)) {    /* validate every input */
    
        for (int rd = 0; custNum[rd]; rd++)
            if (!isspace((unsigned char)custNum[rd]))
                custNum[wrt++] = custNum[rd];
        custNum[wrt] = 0;
        
        std::cout << "Customer No.: " << custNum << '\n';
    }
}

两个循环计数器rd(读取位置)和wrt(写入位置)仅用于循环原始字符串并删除找到的任何空格,在离开循环时再次nul终止

使用/输出示例

$ ./bin/readcustnum
Please enter values for the following:
Customer No.: 7877 323 2332
Customer No.: 78773232332

还要看看Why is “using namespace std;” considered bad practice?C++: “std::endl” vs “\n”。现在养成好习惯比以后改掉坏习惯要容易得多。。。仔细研究一下,让我知道是否有问题。

,

除std :: getline之外,如果要使用C样式的字符串,请尝试以下代码:

int main() {
    char* str = new char[60];
    scanf("%[^\n]s",str);  //accepts space a a part of the string (does not give UB as it may seem initially
    printf("%s",str);
    return 0;
}

此外,如果您绝对需要将其用作数字,请使用atoi

int ivar = std::atoi(str);

PS不要忘了(!!危险!)

char* str;
gets(str);
puts(str);
,

cin >> int_variable到达第一个不是数字有效部分的字符时,将停止读取输入。 C ++不会将空格视为数字的一部分,因此一旦遇到数字,它将立即停止读取。

您可以改用std::getline读入字符串,然后在转换为整数之前从字符串中删除空格。也许在这种情况下,您甚至不需要整数就可以将其保留为字符串。