我的输入是否正确写入我的数组

Is my input being written properly to my array?

本文关键字:我的 数组 输入 是否      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctype.h>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
char buffer[100]= {};
int length = 0;
cout << "Enter a string: ";
do
{
    cin >> buffer;
}
while(cin.eof());
length = strlen(buffer);
int squareNum = ceil(sqrt(length));
cout << squareNum;
cout << buffer;
}

基本上我要做的是用我输入的字符串填充一个字符数组。但是我相信它只是写入数组,直到出现空格。

Ex. 
Input: this is a test
Output: this
Input:thisisatest
Output:thisisatest

为什么它停在空间?我很确定它必须与 .eof 循环有关

while(cin.eof());

你不太可能在阅读一个单词后进入eof()。 你想要

while(! cin.eof());

或者更准确地说是循环之类的东西

while(cin >> buffer);

或者,更好的是,省去字符数组并使用 stringgetline .

您可以使用std::getline()来获取每一行,例如

std::getline (std::cin,name)

这样,您的输入就不会被空格分隔符分隔

与其使用 cin.eof() ,不如尝试类似的东西:

std::string a;
while (std::getline(std::cin, a))
{
    //...
}