Dylan Galea
Dylan Galea

Reputation: 115

C++ Cin input to array

I am a beginner in c++ and I want to enter a string as character by character into an array , so that I can implement a reverse function .. However unlike C when the enter is hit a '\n' is not insterted in the stream.. how can I stop data from being entered ?

my code is :

#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;
}

Upvotes: 5

Views: 28739

Answers (2)

Stack Danny
Stack Danny

Reputation: 8126

Since you tagged your question as C++ (and not C) why not actually solve it with the modern C++ headers (that do exactly what you want, are tested, save and work really fast (rather than own functions))?

#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;
}

output:

Enter a string: Hello Test 4321
1234 tseT olleH

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409176

When you read character by character, it really reads characters, and newline is considered a white-space character.

Also the array will never be terminated as a C-style string, that's not how reading characters work. That means your loop condition is wrong.

To begin with I suggest you start using std::string for your strings. You can still read character by character. To continue you need to actually check what characters you read, and end reading once you read a newline.

Lastly, your reverse function does not work. First of all the loop itself is wrong, secondly you return the pointer to the original string, not the "reversed" array.


To help you with the reading it could be done something like

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

    str += ch;  // Append character to string
}

Do note that not much of this is really needed as shown in the answer by Stack Danny. Even my code above could be simplified while still reading one character at a time.

Upvotes: 7

Related Questions