简体   繁体   中英

Reading individual characters from a string constant in C using sscanf

I'm trying to read individual characters from a string constant passed into a function and put them into an array. The end result i want is an a string array that is the same string as the string constant. This is my code:

for(int i = 0; i < string_length; i++)
{
    sscanf(string, "%c", &array[i]);
}

When string is "string" all i get is a string_length sized array with every value being an s. Any ideas?

sscanf cannot remember your index positioning and automatically increment pointers. So, effectively, it ends up reading the first character each time you call it in the loop.

Try as below

sscanf(string+i, "%c", &array[i]); 

Additional Note: You can as well use strcpy or memcpy to copy the string into a character array. I hope you have a good enough reason for using sscanf for this.

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