Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert input string into a char array

Tags:

c++

arrays

string

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
like image 403
Syngularity Avatar asked Apr 30 '26 11:04

Syngularity


1 Answers

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;
like image 145
john Avatar answered May 03 '26 01:05

john



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!