C ++ Cin输入到数组

Dyl*_*lea 5 c++ arrays cin

我是c ++的初学者,我想将一个字符串作为一个字符一个字符地输入到数组中,以便我可以实现反向功能..但是,与C不同,当按下回车键时,流中不会插入'\ n' ..如何停止输入数据?

我的代码是:

#include<iostream>
#include<array>
#define SIZE 100
using namespace std;

char *reverse(char *s)
{
    array<char, SIZE>b;
    int c=0;
    for(int i =(SIZE-1);i>=0;i--){
        b[i] = s[c];
        c++;
    }

    return s;
} 

int main()
{
    cout<<"Please insert a string"<<endl;
    char a[SIZE];
    int i=0;
    do{
        cin>>a[i];
        i++;
    }while(a[i-1]!= '\0');

    reverse(a);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*nny 6

既然您将问题标记为C++(而不是C),为什么不使用现代的C ++头(实际上正是您想要的,经过测试,保存并真正快速运行(而不是自己的函数))真正解决了这个问题?

#include <string>
#include <algorithm>
#include <iostream>

int main(){
    std::string str;
    std::cout << "Enter a string: ";
    std::getline(std::cin, str);

    std::reverse(str.begin(), str.end());

    std::cout << str << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Enter a string: Hello Test 4321
1234 tseT olleH
Run Code Online (Sandbox Code Playgroud)


Som*_*ude 5

当您逐个字符地读取字符时,它实际上是读取字符,而换行符被视为空白字符

而且,数组永远不会以C样式的字符串终止,这不是读取字符的工作方式。这意味着您的循环条件是错误的。

首先,我建议您开始使用std::string字符串。您仍然可以逐个字符地阅读。要继续,您需要实际检查您阅读的字符,并在阅读换行符后结束阅读。

最后,您的reverse功能不起作用。首先,循环本身是错误的,其次,您将指针返回到原始字符串,而不是“反向”数组。


为了帮助您阅读,可以执行以下操作

std::string str;
while (true)
{
    char ch;
    std::cin >> ch;
    if (ch == '\n')
    {
        break;  // End loop
    }

    str += ch;  // Append character to string
}
Run Code Online (Sandbox Code Playgroud)

请注意,如Stack Danny的答案所示,并不需要太多。即使我上面的代码也可以简化,同时仍一次读取一个字符。