Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I use sscanf to get names and print them out the way i want them to
    primarykey
    data
    text
    <p>I'm making a program that takes names from the user seperated by commas. The program allows the user to put as many or as little spaces as they want between the commas. So for example:</p> <p>If I were to type something like</p> <pre><code>Smith, John </code></pre> <p>or</p> <pre><code>Smith,John </code></pre> <p>I would want to print out </p> <pre><code>John, Smith </code></pre> <p>The thing is though my program does not properly process the following examples above; it works if the input was something like</p> <pre><code>Smith , John </code></pre> <p>or</p> <pre><code>Smith ,John. </code></pre> <p>Here is my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #define LINESIZE 128 int get_last_first(FILE *fp); int main (void) { get_last_first(stdin); } /*takes names in the format [LASTNAME],[FIRSTNAME]*/ int get_last_first(FILE *fp) { char first[LINESIZE]; char last[LINESIZE]; char line[LINESIZE]; size_t i; while(1) { printf("Enter your last name followed by a comma and your first name\n"); /*if we cant read a line from stdin*/ if(!fgets(line, LINESIZE, fp)) { clearerr(stdin); break; /*stop the loop*/ } /*goes through the line array and checks for non-alphabetic characters*/ for(i = 0; i &lt; strlen(line); i++) { if(!isalpha(line[i])) { /*if it sees a space hyphen or comma, it continues the program*/ if((isspace(line[i]) || line[i] == ',') || line[i] == '-' ) { continue; } else { return -1; } } } if(sscanf(line, "%s , %s", last, first)) { printf("%s, %s", first, last); return 1; } return 0; } } </code></pre> <p>Is it because I am not using sscanf properly?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload