我使用字符数组来获取用户的输入,然后显示输出。但是,每次我输入之间有空格的值时,仅打印空格之前的第一个单词。
例如,这是我输入的内容:
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/