简体   繁体   中英

Split string into different variables

Hey guys! I'm new to C, so i would like help in one problem. I have to separate a string and put him into diferent variables. Imagine, Sol 3 5 would result in something like:

var1=Sol  
var2=3  
var3=5 

I tried to use the scanf, but it stoped in the first space :/ .
Thanks in advance!
Cheers!

EDIT: Isn't my homework, i'm just practicing, but i really want to now how I can do this :) . The code I have now is this:

int main () {  
    char var1[10],var2[10],var3[10],func;  
    fgets(func, 20, stdin);   
    fscanf(func,"%s %d %d", var1,var2,var3);  
    printf("%s %d %d", var1,var2,var3);  
    return 0;  
}

strtok is the function you need:

 #include <string.h>

 char* str = "Sol 3 5";
 char* ptr;
 char* saved;
 ptr = strtok_r(str, " ", &saved);
 while (ptr != NULL)
 {
   printf("%s\n", ptr);
   p = strtok_r(NULL, " ", &saved);
 }

Just a note: this function modifies the original string, placing end of string tokens (nulls, \\0 ) in place of delimiters.

Ok scanf would be good anyway, but I'm not gonna help you if you don't state clearly if it's homework..

After the edit and code posted

Your problem is that you are lying to the compiler. Don't do that. It doesn't like it :)

You ask the compiler to read a string and 2 integers ... but then tell it to put the results in a char arrays (correct only for the first conversion)

             /* char[] but %d wants pointer to int */
    fscanf(func,"%s %d %d", var1,var2,var3);
                         /* all var1, var2, and var3 are arrays of char! */

Try declaring your variables as

    char var1[10];
    int var2,var3;

Oh! func is declared as plain char. You probably want something else.

Once you declare your variables like that, you need to change the scanf call an pass the address of the ints, rather than their (uninitialized) values.

There is a function similar to scanf called sscanf . It works just the same, but it reads to values from a string instead of from a file:

sscanf("Sol 3 5", "%s%d%d", v1, &v2, &v3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM