Question:
Initialise char array c++?
Ben Chambers
2012-04-25 02:48:10 UTC
Need help with this:

Write a program that:

- Initializes a char array with the letters 'a', 'b', 'c'

- Prints out the array on screen


I'm trying to have the user input the chars with this code:

#include


int main()
{
using namespace std;
int counter = 0;
string set[3];



while(counter <=2)
{
printf ("enter char for location %d:", counter);
scanf ("%c", &set[counter]);
counter++;
}
}

However it doesn't seem to work properly. Can anyone tell me what is wrong here and how to have the chars printed out on-screen individually?

Many Thanks!

Ben
Three answers:
Steve
2012-04-25 04:07:58 UTC
include

using namespace std;



int main(){

int counter = 0;

char set[3];



//read input from console

while (counter <= 2)

{

printf ("enter char for location %d:", counter);

fflush(stdin);

scanf ("%c", &set[counter]);

counter++;

}



//transverse the char array and print to console

counter = 0;

while (counter <= 2){

cout << set[counter];

counter++;

}

return 0;

}



Personally I would have not used printf or scanf instead I would have used cout and cin in C++ but that is up to you. And yes you did not have to read it in from the console but that is how you would.
?
2012-04-25 15:02:12 UTC
you are trying too hard



#include

int main(void){

char set[]={"abc"};

cout << set;

return 0;

}

if you want users to input the string:



#include

int main(void){

char set[256];

cout << "enter some characters: ";

cin >> set;

cout << "you entered: ";

cout << set;

return 0;

}
Rainmaker
2012-04-25 10:37:30 UTC
Eh? Your question was about init char array, this is how you init a char array:



char arr[3] = { 'a', 'b', 'c' } ;


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...