1

The problem I am having is I need to be able to store 2 values from a single line of user input into a single char array. The format will be "input1 input2" where the input1 is a string like 'C2' and input2 is an integer or double like '1.25' and the user will input these values with only a space to separate them. Example:

User Input
C2 1.25

Another thing is I am using the Ch programming language which is a superset of C and a subset of C++. So far I am just learning that some C code does not work in my IDE (ChIDE). I haven't learned much c++ yet. Currently in the book I am reading I am now at the transition point between Ch and C / C++.

So far I have tried a few lines of code, but my book doesn't have an example of scanning for multiple user inputted values in a single line and online I have found this fgets code that seems to work, but I can't make it work with a 2D array.

char userNoteName[15][15];
//15 is arbitrary, ideally I want to use variables
//and that the number of inputted values would be unknown.
printf("Enter notes one at a time, in the format A#4 3,\n");
printf("where the first string is the note, and the number\n");
printf("that follows is the duration.\n");
printf("Type Q when you are done entering notes.\n");
fgets(userNoteName,15,stdin);
printf("%s",userNoteName);

I have also tried using two arrays since I don't completely understand the fgets function, and I don't believe my project requires it since it isn't present in the book yet.

Here is my original line of thinking.

char userNoteName[2][2];
scanf("%s%s", &userNoteName[0][0]);
printf("%s\n", userNoteName);

Though this is wrong because the scanf isn't properly formatted. I think I need to find a better learning resource for coding. Even online I am struggling with finding something that resembles this idea.

Codero
  • 11
  • 1

1 Answers1

0

I don't know Ch, but this is how you'd do it in C:

char userNoteName[3];
float userFloatValue;
scanf("%s %f", userNoteName, &userFloatValue);

%s is for reading a word as a string, and %f reads a float

Note that in order to hold a 2-character string like C2, the variable has to be declared to hold 3 characters, to allow for the null terminator. If string1 can be longer, you'll need to declare the variable of the appropriate size, just remember to add 1 for the null.

Barmar
  • 741,623
  • 53
  • 500
  • 612