c++ - 空格后的字符不会被打印出来

标签 c++ arrays char character limit

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

例如,这是我输入的内容:

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” 。现在养成好习惯比以后改掉坏习惯容易得多...仔细检查一下,如果有问题请告诉我。

关于c++ - 空格后的字符不会被打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63698129/

相关文章:

c++ - C/C++错误:超出范围读取。寻找错误的内存地址

php - 对数组进行排序,其中包含一些按天排序的日期,例如 php 中的星期日、星期一等

c - 调整数组大小和复制哪个更好?

java - 读取一个文本文件并存储每个出现的字符

c++ - 无方法抽象类?

c++ - 将函数应用于图像的每个像素

c++ - 无竞争目录遍历 (C++)

java - 不使用循环搜索字符串数组

c - 如何从字符数组中提取子字符数组

c++ - 从字符串中提取单个字符并将其转换为 int