I have a string "14 22 33 48". I need to insert each of the values in the string into the respective location in the array:
int matrix[5];
so that
matrix[0] = 14;
matrix[1] = 22;
matrix[2] = 33;
matrix[3] = 48;
How do I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Robust string processing in C is never simple.
Here’s a procedure that popped immediately to mind for me. Use
strtok()to break the string into individual tokens, then convert each token to an integer value usingstrtol().Things to be aware of:
strtok()modifies its input (writes 0 over the delimiters). This means we have to pass it a writable string. In the example below, I create a buffer dynamically to hold the input string, and then pass that dynamic buffer tostrtok(). This guarantees thatstrtok()is operating on writable memory, and as a bonus, we preserve our input in case we need it later.Also,
strtol()allows us to catch badly formed input; the second argument will point to the first character in the string that wasn’t converted. If that character is anything other than whitespace or 0, then the string was not a valid integer, and we can reject it before assigning it to our target array.