Syngularity
Syngularity

Reputation: 824

Convert input string into a char array

My problem is that, I have a string that I get from keyboard and want to save it in to a char array. After I get the array I want to turn it in to a number or something.

I tried many thing but it's doesn't work. This is my best solution so far:

string input_string;
char char_string[20];

cout << "type in some input text:$" << endl;
cin >> input_string;

strcpy(char_string, input_string.c_str());

for (int i = 0;  i < 20 ; i++)
{
    switch(char_string[i])
    {
        case 'a' : cout << "a" << endl; break;
        case 'b' : cout << "b" << endl; break;
        case 'c' : cout << "c" << endl; break;
        case 'd' : cout << "d" << endl; break;
        case 'e' : cout << "e" << endl; break;
        case 'f' : cout << "f" << endl; break;
        ...

but when I run this code I get something thy i don't expect. If the input is random random

I get this:

r
a
n
d
o
m
contain uavialba char
contain uavialba char
contain uavialba char
contain uavialba char
contain uavialba char
contain uavialba char
contain uavialba char
contain uavialba char
contain uavialba char
v
contain uavialba char
z
contain uavialba char
contain uavialba char

But i want this:

r
a
n
d
o
m

r
a
n
d
o
m

Upvotes: 2

Views: 23178

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

It is preferable to write to not depend on the size and're using std::string.

//g++ -std=c++0x sample.cpp
#include <iostream>
#include <algorithm>

using namespace std;

int main(){
    string input_string;

    cout << "type in some input text:$" << endl;
    cin >> input_string;

    for(auto c : input_string)
        cout << c << endl;

    for_each(input_string.begin(), input_string.end(), [](char c){ cout << c << endl; });

    return 0;
}

Upvotes: 1

john
john

Reputation: 87959

The problem is here

for (int i = 0;  i < 20 ; i++)

You always output 20 characters. You should stop outputting when you get to the end of the string.

for (int i = 0;  char_string[i] != '\0' ; i++)

C style strings have a '\0' character at the end, you should test for this.

Seems the other error is that you read a word instead of a line. Instead of this

cin >> input_string;

try this

getline(cin, input_string);

getline reads a whole line, >> reads a single word.

BTW there's an easier way to write the code inside the for loop. You don't need switch, just do this instead

cout << char_string[i] << endl;

Upvotes: 7

David
David

Reputation: 28178

You don't need char_string at all. Just pretend input_string is an array of chars (it does contain one, after all). For example, input_string[7] will give you a char.

for(char c : input_string)
{
    switch(c)
    {
        case 'a' : cout << "a" << endl; break;
        case 'b' : cout << "b" << endl; break;
        ...

Upvotes: 1

Related Questions