0

I am trying to create a do-while loop that scans two variables but when I type "exit", I want the function to go out the loop. This is my code:

char var1;
char var2;
do {
    scanf("%s %s", &var1, &var2);
} while ("Some argument that I don't know")

I tried (strcmp(&var1,'quit') != 0) and things like that as argument but it doesn't work.

jps
  • 20,041
  • 15
  • 75
  • 79
786534854
  • 3
  • 1

2 Answers2

1

Your variable type is wrong. It must be an array of char to hold a text string.

Use strcmp to check for "exit"

Something like:

char var1[32] = {0};
char var2[32] = {0};
do {
    scanf("%31s %31s", var1, var2);
}while ((strcmp(var1, "exit") != 0) && (strcmp(var2, "exit") != 0));

Another approach so that the program exits the first time someone inputs "exit" could look like:

#include <stdio.h>

int main() {
char var1[32] = {0};
char var2[32] = {0};
do {
    scanf("%31s", var1);
    if (strcmp(var1, "exit") == 0) break;
    scanf("%31s", var2);
    if (strcmp(var2, "exit") == 0) break;
    printf("%s %s\n", var1, var2);
}while (1);

return 0;
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • OK! I test that and now it works! Thanks! But is it possible to make it so when I write "exit" for the first time, the program goes out of the loop directly? Because I want to either give a "value" to the two variables or write "exit" and the directly go out of the loop. – 786534854 Mar 31 '18 at 11:31
0

I think one of your issues is that you're trying to scan a string into a char variable:

char var1 creates a new char variable, which can hold a single character at a time.

%s in scanf scans a string - a character array.

Initialising your variables as:

char * var1;
char * var2;

Will allow scanf to scan strings into them. Your strcmp line from before should probably work after that - though you'll need an additional condition if you want to check both variables.

Sean
  • 212
  • 1
  • 10