Store two integers from a String in C
I am trying to write a program that prints two numbers from a string.
For example, string = '20,66' I am trying to break this string apart so I can store '20' and '66' into two sepa开发者_开发问答rate variables.
Here is the code I am working on:
#include <stdio.h>
char line[80];
int main(void)
{
// Variables
int start_number, end_number;
int i, j;
while(1)
{
printf("Enter a number: ");
fgets( line, sizeof(line), stdin);
// How to find Comma
for( i=0; i < strlen(line); i++)
{
if(line[i]==',') break;
}
// How to find two numbers
for(j = 0; j < i; j++)
{
printf("1: %c\n", line[j]);
}
for(j = i + 1; j < strlen(line); j++)
{
printf("2: %c\n", line[j]);
}
if (strcmp(line, "quit\n") == 0)
{
printf("Now terminating program...");
break;
}
}
}
So far, I am only able to store single digit variables and for some reason prints an extra line.
Any suggestions or advice will be appreciated.
Quite simple:
const char *text = "20,30";
const char *rest = 0;
int first = strtol(text, &rest, 10); // input, pointer to remaining string, base (10 = decimal)
rest += 1; // skip the comma; this is error prone in case there are spaces!
int second = strtol(rest, NULL, 10); // not interested in remaining string, so pass NULL this time
Look into scanf and its relatives:
#include <stdio.h>
int main() {
int x, y;
sscanf("22,33", "%d,%d", &x, &y);
printf("Scanned vars: %i %i\n", x, y);
}
tmp]$ ./a.out
Scanned vars: 22 33
It's possible to introduce security vulnerabilities so be sure to read and understand the section on security so that you have enough storage for the values you're trying to scan.
One of many approaches: Once you find the comma, you can change the comma to (char)0
. Then you will have two strings, one will be line
the other one will be at line+comma_offset+1
. Both are just the numbers and can be passed to atoi
.
This trick works due to the way C strings are implemented—the end of the string is a 0. So, you take a string:
'1' '2' ',' '3' '4' 0x00
|
line
and replace the comma with a null:
'1' '2' 0x00 '3' '4' 0x00
| |
line str_2
then you have two C strings. This is how strtok
and strtok_r
work.
Perhaps you dont want to have "1: " and/or a NEWLINE ("\n") printed within the for loop. Change this:
for(j = 0; j < i; j++)
{
printf("1: %c\n", line[j]);
}
to this:
printf("1: ");
for(j = 0; j < i; j++)
{
printf("%c", line[j]);
}
printf("\n");
#include <stdio.h>
char line[80];
int main(void)
{
// Variables
int start_number, end_number;
int i, j;
while(1)
{
printf("Enter a number: ");
fgets( line, sizeof(line), stdin);
for( i=0; i < strlen(line); i++)
{
char num[];
if(line[i]!=','){
num[j++] = line[i];
}
else{
for(int x =0 x<strlen(num); x++)
printf("Number :%c", num[x]);
j=0;
}
}
}
}
精彩评论