David Vlcek
David Vlcek

Reputation: 21

How do you include spaces in a scanf string?

This program works as long as the "major" variable is only one word. For example, CIS is a valid input but Computer Information Systems is not. How do I fix this?

#include<stdio.h>

int main()
{
char major [51];
int classes;

printf("What is your major? ");
scanf("%50s", major);

printf("How many classes are you taking this semester? ");
scanf("%d", &classes);

printf("Your major is %s and you are taking %d classes this semester.\n", major, classes);
}

Upvotes: 1

Views: 4742

Answers (2)

ad absurdum
ad absurdum

Reputation: 21361

You can use %50[^\n] to match up to 50 characters until a newline is encountered, and store them in major[]. The newline will be left behind in the input stream, but the %d conversion specifier automatically skips over leading whitespace characters.

Note that if the user enters more than 50 characters, there will be extra characters in the input stream to discard before calling scanf() to get the number of classes.

Upvotes: 3

twain249
twain249

Reputation: 5706

Your problem is scanf stops at the first white space. What you need to do is keep reading until you read the end line character.

It's possible to do this with scanf but there are better options. fgets() comes to mind immediately. https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

A few searches on Stack overflow will yield a ton of topics about the scanf() vs fgets() vs others. Using fscanf() vs. fgets() and sscanf()

Upvotes: 2

Related Questions