I am trying to figure out if there is a simpler way in C to scanf() a certain part of an inputted number by the user.
Following the code:
printf("Enter opcode:\n");
scanf("%1d", &opcode);
If an user inputs the number 240, scanf("%1d", &opcode); will save the first digit only in opcode
Is there a way to select only the last two digits?
The easiest way to handle the task is to read the input as a string. Then perform validations, e.g. number of characters entered, that last two characters are valid hex-digits, etc.. and then use your conversion of choice to convert the last two digits to an unsigned value.
When taking input, it is recommended that you use a line-oriented function to read the entire line and then parse what you need from the line. The benefits are three-fold (1) you get an independent validation of the read; (2) you get an independent validation of the conversion; and (3) what remains in the input buffer doesn't depend on the scanf conversion specifier used.
A short example would be:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXC 1024 /* if you need a constant #define one (or more) */
int main (void) {
char buf[MAXC]; /* buffer to hold line (don't skimp on size) */
printf ("Enter opcode: "); /* prompt */
if (fgets (buf, MAXC, stdin)) { /* read entire line */
char *p; /* pointer - to set to last 2 digits */
size_t len; /* length of the string entered */
buf[(len = strcspn (buf, "\r\n"))] = 0; /* get length/trim '\n' */
if (len < 2) { /* validate at least 2 characters entered */
fputs ("error: minimum 2-characters required.\n", stderr);
return 1;
}
p = buf + len - 2; /* set p to point to next to last char */
if (!isxdigit(*p) || !isxdigit(*(p+1))) { /* validate hex digits */
fputs ("error: last 2 chars are not hex-digits.\n", stderr);
return 1;
}
printf ("last 2 digits: %s\n", p); /* output last 2 digits */
/* perform conversion of choice here
* (suggest strtoul or sscanf)
*/
}
return 0;
}
(note: choosing the conversion is left to you. Also note how you handle the '\n' included in the buffer by fgets is also up to you. Above it is simply overwritten with the nul-terminating character)
Example Use/Output
$ ./bin/opcodelast2
Enter opcode: 240
last 2 digits: 40
Other results:
Enter opcode: 40
last 2 digits: 40
Enter opcode: 3240
last 2 digits: 40
Enter opcode: 324a
last 2 digits: 4a
Enter opcode: 4g
error: last 2 chars are not hex-digits.
Enter opcode: 4
error: minimum 2-characters required.
You can adjust the tests (e.g. isdigit or isxdigit) to meet your particular needs. You can (and should) include a test that len < MAXC - 1 to ensure the entire line was read and that additional characters do not remain unread (e.g. a cat went to sleep on the keyboard). Let me know if you have any further questions.
The code of #Craig Estey can be broken if you enter a big number.
int main()
{
char str[100];
do {
scanf("%99s", str);
} while (strlen(str) < 2);
int opcode = atoi(str + strlen(str) - 2);
}
Yes, it's not perfect because it's break when you enter a string with more than 100 char.
But, you can replace the scanf by another function who can take a infinite string len.
Related
The following piece of code is continuously asking for me to give it 1 input, meaning that when I press "Enter" it does not skip to the next scanf instead just goes to the next line on console and waits for input.
int main()
{
int i, print, line ;
char oFile[50] , iFile[50] = "listsource.c" ;
printf("Please enter the name of the input file: ") ;
scanf("%s", iFile) ;
printf("Please enter 0 to print to console, 1 to print to another file: ") ;
scanf("%d", &print) ;
printf("%s", iFile) ;
}
I am trying to give it a default value of "listsource.c" if no input is entered, have already tried fgets and I have the same problem
Try this:
#include <stdio.h>
int main()
{
char hello[81];
fgets(hello, 80, stdin);
hello[strlen(hello) - 1 ] = '\0';
// OR
gets(hello);
}
It worked with Online C Compiler.
You will have to strip the newline although...gets() will do the work, but is it dangerous as it will read any number of character regardless of the amount specified by you when you declared the variable it is going into. Thus it will overwrite past the memory allocated by the compiler. (Yes, this is allowed by C. In C, the programmer is expected to know what he is doing, so he gets all the powers he wants!)
All scanf() conversion specifiers except "%c", "%[..]" and "%n" ignore leading whitespace. A '\n' is whitespace. Using scanf() you can press Enter until your finger falls off using the "%d" conversion specifier and it will never be read. scanf() will simply discard all whitespace and continue blocking waiting on valid input or EOF.
That is just one, of the many, many pitfalls scanf() has for new C programmers. That is why it is highly recommended that you use fgets() for ALL user input. With a sufficient size buffer (character array), fgets() will consume an entire line-at-a-time (including the trailing '\n'). This greatly simplifies input because what remains in stdin after the user presses Enter does not depend on whether a scanf() matching-failure occurred.
To remove the trailing '\n' from the end of the buffer filled by fgets(), simply use strcspn() as follows:
iFile[strcspn (iFile, "\n")] = 0; /* trim \n from end of iFile */
If you do need to convert the contents of your buffer, simply use sscanf() providing your buffer as the first argument, the remainder just as you would use scanf() -- but on any failure, nothing is left in stdin because you have completely read the user-input with fgets().
If you had attempted to read an int with scanf() and the user slipped and hit 'r' reaching for '4', then a matching-failure occurs and character extraction from stdin ceases leaving 'r' in stdin unread. If you are taking input in a loop -- you have just created an infinite loop...
In your case here asking the user to enter 0 or 1, there is no need for numeric conversion to begin with. Simply read the input into a buffer with fgets() and then check if the first character in the buffer is '0' or '1' (the ASCII digits). No conversion required.
Don't use MagicNumbers (e.g. 50) in your code. If you need a constant, #define one, or use a global enum to accomplish the same thing, e.g.
#define MAXFN 50 /* if you need a constant, #define one (or more) */
#define MAXC 1024
int main (void)
{
char buf[MAXC], /* oFile[MAXFN] ,*/ iFile[MAXFN];
(note: if programming on a microcontroller, reduce the max number of characters for your read-buffer (MAXC) accordingly, otherwise, for general PC use a 1K buffer is fine)
Putting it altogether, and adding a "print to another file - not implemented", to handle the user entering 1 as asked, you could do:
#include <stdio.h>
#include <string.h>
#define MAXFN 50 /* if you need a constant, #define one (or more) */
#define MAXC 1024
int main (void)
{
char buf[MAXC], /* oFile[MAXFN] ,*/ iFile[MAXFN];
fputs ("Please enter the name of the input file: ", stdout);
if (!fgets (iFile, MAXFN, stdin)) { /* read ALL user input with fgets() */
puts ("(user cancled input)"); /* validate, if manual EOF return */
return 0;
}
iFile[strcspn (iFile, "\n")] = 0; /* trim \n from end of iFile */
for (;;) { /* loop continually until valid input from user or EOF */
fputs ("\nPlease enter 0 to print to console, "
"1 to print to another file: ", stdout);
if (!fgets (buf, MAXC, stdin)) { /* read ALL user input with fgets() */
puts ("(user cancled input)"); /* validate, if manual EOF return */
return 0;
}
if (*buf == '0') { /* no need to covert to int, just check if ASCII '0' */
puts (iFile);
break;
}
else if (*buf == '1') { /* ditto -- just check if ASCII '1' */
puts ("print to another file - not implemented");
break;
}
fputs (" error: invalid input, not 0 or 1\n", stderr); /* handle error */
}
}
(note: when you need the user to provide specific input, loop continually until you get what you require, or until the user generates a manual EOF by pressing Ctrl + d (or Ctrl + z on windows))
Example Use/Output
Intentionally pressing Enter alone for the first input and providing invalid input for the next two, you would have:
$ ./bin/console_or_file
Please enter the name of the input file: myInputFilename.txt
Please enter 0 to print to console, 1 to print to another file:
error: invalid input, not 0 or 1
Please enter 0 to print to console, 1 to print to another file: bananas
error: invalid input, not 0 or 1
Please enter 0 to print to console, 1 to print to another file: 2
error: invalid input, not 0 or 1
Please enter 0 to print to console, 1 to print to another file: 0
myInputFilename.txt
Look things over and let me know if you have further questions.
I want to write a C program to add the numbers given by the user as long as they want... can anyone fix this program?
I tried to use a do-while loop.
Any other suggestions to improve my code?
I am unable to end the loop.
#include <stdio.h>
int main()
{
int x=0, sum = 0, y=0, fu;
printf("first number you want to add:\n");
scanf("%d", &x);
printf("next number you want to add:\n");
scanf("%d", &y);
x=x+y;
do
{
printf("do you want to add numbers further? \nEnter 0:Yes or 1:No: \n");
scanf("%d", &fu);
printf("next number you want to add:\n");
scanf("%d", &y);
x=x+y;
}
while(fu>0);
sum=x;
printf("Sum of all integers = %d\n", sum);
return 0;
}
Ask for the 3rd and further numbers in an if and modify your while:
scanf("%d", &fu);
if(fu == 0) {
printf("next number you want to add:\n");
scanf("%d", &y);
x=x+y;
}
}
while(fu == 0);
Your prompt says:
Enter 0:Yes or 1:No:
so you need to continue that loop if 0 was entered:
while(fu == 0);
Also, you don't need to take another y after non-0 input.
The key to taking any input, either from the user, or from a file, is to validate every single input by checking the return. You cannot blindly use a variable holding input until you know whether the input succeeded or failed. Otherwise, if the input fails and you use a variable whose value is indeterminate, you invoke undefined behavior.
Also, if you are using a formatted input function such as scanf(), if a matching failure occurs, character extraction from stdin ceases at that point and the characters causing the failure are left in stdin -- unread, just waiting to bite you again on your next attempted input.
Instead, if you use a line-oriented input function such as fgets() or POSIX getline(), you read an entire line at a time. You can simply call sscanf() on the buffer filled by fgets() to convert a numeric input to an integer value. That way it does not matter if the conversion succeeds or fails, you do not leave anything unread in the input stream.
Just as you must validate every input, you so too must validate every conversion. Whether using sscanf() or strtol(), etc... a failure to validate every conversion will likely lead to undefined behavior when you fail to detect the conversion failure.
Another benefit of using fgets() or getline() is they read and store the '\n' from the user pressing Enter. So rather than having to prompt "do you want to add numbers further? \nEnter 0:Yes or 1:No: \n" and have to worry about yet another input and conversion -- you simply check if Enter was pressed on an empty line to know the user completed input (e.g. the first character in the buffer filed by fgets() is the '\n' character).
You also have to handle an invalid input correctly. What if the user enters "bananas" instead of a number?
Putting it altogether, you could do something similar to:
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (void) {
char buf[MAXC]; /* buffer (character array) to hold all user input */
int sum = 0, n = 0; /* sum and count of numbers */
puts ("press ENTER alone to exit:\n"); /* display instructions */
while (1) { /* loop continually */
int tmp; /* temporary int to add to sum */
/* prompt based on 1st or subsequent number */
fputs (n ? "next number : " : "first number : ", stdout);
/* read and validate input, break on EOF or empty line */
if (!fgets (buf, MAXC, stdin) || *buf == '\n') {
puts ("---------------------");
break;
}
/* validate conversion to int */
if (sscanf (buf, "%d", &tmp) == 1) { /* on success */
sum += tmp; /* add to sum */
n += 1; /* increment count */
}
else /* handle error */
fputs (" error: invalid integer input.\n", stderr);
}
printf (" sum : %d\n", sum); /* output final sum */
}
Example Use/Output
$ ./bin/sum
press ENTER alone to exit:
first number : 10
next number : -20
next number : 30
next number : -40
next number : bananas
error: invalid integer input.
next number : 50
next number :
---------------------
sum : 30
There are several ways to approach this, and if you wanted the user to be able to enter more than one-number per-line, you could parse buf with strtol() to extract all values. (you can do the same with sscanf() using an offset from the beginning of the string and the characters consumed on each conversion from the "%n" specifier) Many ways to go.
Let me know if you have further questions.
So I want to write a program to check if user enter. Say requirement is 4 digits number, if user enters 5 then program keeps asking user to renter exactly 4 digit number.
I got the working code like this: basically use scanf to read in a string value, then use strlen to count number of digits. If user enters the correct digit, then I use atoi to convert that string into an int, which I will use for later.
Say requirement is 4 digit number:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int digit, mynumber;
int digit = 5;
char str[5];
/* Checking if enter the correct digit */
do {
printf("Enter a %d digit number\n", digit);
scanf("%s", &str);
if (strlen(str) != digit) {
printf("You entered %d digits. Try again \n", strlen(str));
} else {
printf("You entered %d digits. \n", strlen(str));
printf("Converting string to num.....\n");
mynumber = atoi(str);
printf("The number is %d\n", mynumber);
}
} while (strlen(str) != digit);
return 0;
}
I want to modify this a bit. Instead of doing char str[5] for 5 digit string. I want to try a dynamic array.
So in place of char str[5], I do this:
char *str;
str = malloc(sizeof(char) * digit);
Running this through the code gives seg fault. Can anyone help me with this?
This is the complete code with the issue
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int mynumber;
int digit = 5;
char *str;
str = malloc(sizeof(char) * digit);
/* Checking if enter the correct digit */
do {
printf("Enter a %d digit number\n", digit);
scanf("%s", &str);
if (strlen(str) != digit) {
printf("You entered %d digits. Try again \n", strlen(str));
} else {
printf("You entered %d digits. \n", strlen(str));
printf("Converting string to num.....\n");
mynumber = atoi(str);
printf("The number is %d\n", mynumber);
}
} while (strlen(str) != digit);
return 0;
}
While you can use the formatted input function scanf to take your input as a string, scanf is full of a number of pitfalls that can leave stray characters in your input stream (stdin) depending on whether a matching-failure occurs. It also has the limitation using the "%s" conversion specifier of only reading up to the first whitespace. If your user slips and enters "123 45", you read "123", your tests fail, and "45" are left in stdin unread, just waiting to bite you on your next attempted read unless you manually empty stdin.
Further, if you are using "%s" without the field-width modifier -- you might as well be using gets() as scanf will happily read an unlimited number of characters into your 5 or 6 character array, writing beyond your array bounds invoking Undefined Behavior.
A more sound approach is the provide a character buffer large enough to handle whatever the user may enter. (don't Skimp on buffer size). The read an entire line at a time with fgets(), which with a sufficient sized buffer ensure the entire line is consumed eliminating the chance for characters to remain unread in stdin. The only caveat with fgets (and every line-oriented input function like POSIX getline) is the '\n' is also read and included in the buffer filled. You simply trim the '\n' from the end using strcspn() as a convenient method obtaining the number of characters entered at the same time.
(note: you can forego trimming the '\n' if you adjust your tests to include the '\n' in the length you validate against since the conversion to int will ignore the trailing '\n')
Your logic is lacking one other needed check. What if the user enters "123a5"? All 5 characters were entered, but they were not all digits. atoi() has no error reporting capability and will happily convert the string to 123 silently without providing any indication that additional characters remain. You have two-options, either use strtol for the conversion and validate no characters remain, or simply loop over the characters in your string checking each with isdigit() to ensure all digits were entered.
Putting that altogether, you could do something like the following:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NDIGITS 5 /* if you need a constant, #define one (or more) */
#define MAXC 1024
int main (void) {
int mynumber;
size_t digit = NDIGITS;
char buf[MAXC]; /* buffer to hold MAXC chars */
/* infinite loop until valid string entered, or manual EOF generated */
for (;;) {
size_t len;
printf("\nEnter a %zu digit number: ", digit); /* prompt */
if (!fgets (buf, sizeof buf, stdin)) { /* read entire line */
fputs ("(user canceled input)\n", stdout);
break;
}
buf[(len = strcspn(buf, "\n"))] = 0; /* trim \n, get len */
if (len != digit) { /* validate length */
fprintf(stderr, " error: %zu characters.\n", len);
continue;
}
for (size_t i = 0; i < len; i++) { /* validate all digits */
if (!isdigit(buf[i])) {
fprintf (stderr, " error: buf[%zu] is non-digit '%c'.\n",
i, buf[i]);
goto getnext;
}
}
if (sscanf (buf, "%d", &mynumber) == 1) { /* validate converstion */
printf ("you entered %zu digits, mynumber = %d\n", len, mynumber);
break; /* all criteria met, break loop */
}
getnext:;
}
return 0;
}
Example Use/Output
Whenever you write an input routine, go try and break it. Validate it does what you need it to do and catches the cases you want to protect against (and there will still be more validations you can add). Here, it covers most anticipated abuses:
$ ./bin/only5digits
Enter a 5 digit number: no
error: 2 characters.
Enter a 5 digit number: 123a5
error: buf[3] is non-digit 'a'.
Enter a 5 digit number: 123 45
error: 6 characters.
Enter a 5 digit number: ;alsdhif aij;ioj34 ;alfj a!%#$%$ ("cat steps on keyboard...")
error: 61 characters.
Enter a 5 digit number: 1234
error: 4 characters.
Enter a 5 digit number: 123456
error: 6 characters.
Enter a 5 digit number: 12345
you entered 5 digits, mynumber = 12345
User cancels input with ctrl+d on Linux (or ctrl+z on windows) generating a manual EOF:
$ ./bin/only5digits
Enter a 5 digit number: (user canceled input)
(note: you can add additional checks to see if 1024 or more characters were input -- that is left to you)
This is a slightly different approach to reading input, but from a general rule standpoint, when taking user input, if you ensure you consume an entire line of input, you avoid many of the pitfalls associated with using scanf for that purpose.
Look things over and let me know if you have further questions.
In your code you have an array of 5 bytes. If the user enters more than 4 digits, scanf will happily overflow the array and corrupt the memory. It will corrupt the memory in both cases, as an array and as a malloc. However, not every memory corruption causes a crash.
So, you need to limit the number of bytes the scanf can read. The way to do it is to use %4s in the format string.
However, in this case you will not be able to detect when the user enters more than 4 digits. You would need at least 1 more byte: str[6] and %5s;
I suggest, instead of using scanf, use getchar. It would allow you to read character by character and count them on the way.
How would I best take input in a program that asks the user to enter a student name separated by a space and then the student score, EX:
zach 85
Because of the null terminator, will there be two enters that i will have to account for? I'm already using two scanfs in my program.
int main()
{
const int row = 5;
const int col = 10;
int i;
char names[row][col];
int scores[row];
int total;
// Read names and scores from standard input into names and scores array
// Assume that each line has a first name and a score separated by a space
// Assume that there are five such lines in the input
// 10 points
for(int i = 0; i<row; i++)
{
printf("Enter student name: \n");
scanf("%s",&names);
scanf("%s", &scores);
}
// Print the names and scores
// The print out should look the same as the input source
// 10 points
for(int i = 0; i<row; i++)
{
printf( "%s %d \n", names[i] /*, scores[i] */ );
}
}
Your type for scores (int scores[row];) does not correspond to your attempt to read scores with scanf (scanf("%s", &scores);). The "%s" conversion specifier is for converting whitespace separated strings, not integers. The "%d" conversion specifier is provided for integer conversions.
Before looking at specifics. Any time you have a coding task of coordinating differing types of data as a single unit, (e.g. student each with a name (char*) and a score (int), you should be thinking about using a struct containing the name and score as members. That way there is only a single array of struct needed rather than trying to coordinate multiple arrays of differing types to contain the same information.
Also, don't skimp on buffer size for character arrays. You would rather be 10,000 characters too long than 1-character too short. If you think your maximum name is 10-16 character, use a 64-char (or larger) buffer to insure you can read the entire line of data - eliminating the chance that a few stray characters typed could result in characters remaining unread in stdin.
A simple stuct is all that is needed. You can add a typedef for convenience (to avoid having to type struct name_of_struct for each declaration or parameter), e.g.
#include <stdio.h>
#define ROW 5 /* if you need a constant, #define one (or more) */
#define COL 64
typedef struct { /* delcare a simple struct with name/score */
char name[COL]; /* (add a typedef for convenience) */
int score;
} student_t;
Now you have a structure that contains your student name and score as a single unit rather than two arrays, one char and one int you have to deal with.[1]
All that remains is declaring an array of student_t for use in your code, e.g.
int main (void) {
int n = 0; /* declare counter */
student_t student[ROW] = {{ .name = "" }}; /* array of struct */
puts ("\n[note; press Enter alone to end input]\n");
With the array of struct declared, you can turn to your input handling. A robust way of handling input is to loop continually, validating that you receive the input you expects on each iteration, handling any errors that arise (gracefully so that your code continues), and keeping track of the number of inputs made so that you can protect your array bounds and avoid invoking Undefined Behavior by writing beyond the end of your array.
You could begin your input loop, prompting and reading your line of input with fgets as mentioned in my comment. That has multiple advantages over attempting each input with scanf. Most notably because what remains unread in the input buffer (stdin here) doesn't depend on the conversion specifier used. The entire line (up to and including the trailing '\n') is extracted from the input buffer and place in buffer you give fgets to fill. You can also check if the user simply presses Enter which you can use to conveniently indicate end of input, e.g.
for (;;) { /* loop until all input given or empty line entered */
char buf[COL]; /* declare buffer to hold line */
fputs ("Enter student name: ", stdout); /* prompt */
if (!fgets (buf, sizeof buf, stdin)) /* read/validate line */
break;
if (*buf == '\n') /* check for empty line */
break;
(note you can (and should) additionally check the string length of the buffer filled to (1) check that the last character read is '\n' ensuring the complete line was read; and (2) if the last char isn't '\n' checking whether the length is equal to the maximum length (-1) indicating that characters may be left unread. (that is left to you)
Now that you know you have a line of input and it's not empty, you can call sscanf to parse the line into the name and score for each student while handling any failure in conversion gracefully, e.g.
/* parse line into name and score - validate! */
if (sscanf (buf, "%63s %d", student[n].name, &student[n].score) != 2)
{ /* handle error */
fputs (" error: invalid input, conversion failed.\n", stderr);
continue;
}
n++; /* increment row count - after validating */
if (n == ROW) { /* check if array full (protect array bounds) */
fputs ("\narray full - input complete.\n", stdout);
break;
}
}
If you are paying attention, you can see one of the benefits of using the fgets and sscanf approach from a robustness standpoint. You get independent validations of (1) the read of user input; and (2) the separation (or parsing) of that input into the needed values. A failure in either case can be handled appropriately.
Putting all the pieces together into a short program, you could do the following:
#include <stdio.h>
#define ROW 5 /* if you need a constant, #define one (or more) */
#define COL 64
typedef struct { /* delcare a simple struct with name/score */
char name[COL]; /* (add a typedef for convenience) */
int score;
} student_t;
int main (void) {
int n = 0; /* declare counter */
student_t student[ROW] = {{ .name = "" }}; /* array of struct */
puts ("\n[note; press Enter alone to end input]\n");
for (;;) { /* loop until all input given or empty line entered */
char buf[COL]; /* declare buffer to hold line */
fputs ("Enter student name: ", stdout); /* prompt */
if (!fgets (buf, sizeof buf, stdin)) /* read/validate line */
break;
if (*buf == '\n') /* check for empty line */
break;
/* parse line into name and score - validate! */
if (sscanf (buf, "%63s %d", student[n].name, &student[n].score) != 2)
{ /* handle error */
fputs (" error: invalid input, conversion failed.\n", stderr);
continue;
}
n++; /* increment row count - after validating */
if (n == ROW) { /* check if array full (protect array bounds) */
fputs ("\narray full - input complete.\n", stdout);
break;
}
}
for (int i = 0; i < n; i++) /* output stored names and values */
printf ("%-16s %3d\n", student[i].name, student[i].score);
}
Example Use/Output
When ever you write an input routine -- Go Try and Break It!. Intentionally enter invalid data. If your input routine breaks -- Go Fix It!. In the code as noted the only check left for you to implement and handle is input greater than COL number of characters (e.g. the cat steps on the keyboard). Exercise your input:
$ ./bin/studentnamescore
[note; press Enter alone to end input]
Enter student name: zach 85
Enter student name: the dummy that didn't pass
error: invalid input, conversion failed.
Enter student name: kevin 96
Enter student name: nick 56
Enter student name: martha88
error: invalid input, conversion failed.
Enter student name: martha 88
Enter student name: tim 77
array full - input complete.
zach 85
kevin 96
nick 56
martha 88
tim 77
While you can use two separate arrays, a single array of struct is a much better approach. Look things over and let me know if you have further questions.
footnotes:
Be aware that POSIX specifies that names ending with suffix _t are reserved for its use. (size_t, uint64_t, etc...) Also be aware you will see that suffix used in common practice. So check before you make up your own (but we no there is no POSIX student_t type).
You are almost there. However you have to make sure you do things cleanly Let's just do this step by step:
Step 1, get ONE name and ONE score
#include <stdio.h>
#define MAX_NAME_LENGTH 30
int main() {
char name[MAX_NAME_LENGTH+1]; /* an array of characters making up ONE name (+1 for terminating NUL char in case of max-length name) */
unsigned int score; /* a score */
scanf("%30s", name); /* scan a name (assuming NO spaces in the name)*/
/* also notice that name has no & in front of it because it already IS a pointer to the array name[MAX_NAME_LENGTH] */
scanf("%u", &score);
printf("%s scored %u in the test\n", name, score);
return 0;
}
(See it run at http://tpcg.io/jS3woS)
STEP 2 -- Iterate to get multiple scores
Now let's read in 5 pairs and then print out 5 pairs.
#include <stdio.h>
#define MAX_NAME_LENGTH 30
/* i called rows iterations here just to provide contrast */
/* you can call them ROWS if you want but it then creates a confusion about name length */
#define ITERATIONS 5
int main() {
char name[ITERATIONS][MAX_NAME_LENGTH+1]; /* an array of names where each name is MAX_NAME_LENGTH long (notice the order) */
unsigned int score[ITERATIONS]; /* score */
int i;
for(i = 0; i < ITERATIONS; i++ ) {
scanf("%30s", name[i]); /* scan a name (assuming NO spaces in the name)*/
/* notice that name[i] has no & in front of it because name[i] is the pointer to the i-th row */
scanf("%u", &score[i]);
}
for(i = 0; i < ITERATIONS; i++ ) {
printf("%s scored %u in the test\n", name[i], score[i]);
}
return 0;
}
See it in action here (http://tpcg.io/iTj4ag)
first look scores and names are is defined as arrays so
scanf("%s",names[i]);
scanf("%s", &scores[i]);
second scores are int so "%d" instead of "%s"
scanf("%s",names[i]);
scanf("%d", &scores[i]);
third, you've already defined int i; so the one in for loop is not really making any sense, do it only at a single place.
fourth, if your input names contains spaces scanf is not the right option
from manual pages of scanf
Each conversion specification in format begins with either the character '%' or the character sequence "%n$" (see below for the distinction) followed by:
· An optional decimal integer which specifies the maximum field width. Reading of characters stops either when this maximum is reached or when a non‐
matching character is found, whichever happens first. Most conversions discard initial white space characters (the exceptions are noted below), and
these discarded characters don't count toward the maximum field width. String input conversions store a terminating null byte ('\0') to mark the end
of the input; the maximum field width does not include this terminator.
few more points you might want to restrict the number of characters to be scanned during scanf to certain limit example "%20s"
Im trying to save a 100 character max string into an array and then print an specified character of the array via an index, yet I get Segmentation error 11, here is the code:`
#include<stdio.h>
#include<stdlib.h>
int main()
{
char str1[100];
int index;
printf("Enter text of max 100 characters: \n");
scanf("%s", str1);
printf("Enter the index to search\n");
scanf("%d", &index);
printf("your char is: %c\n", str1[index]);
return(0);
}
`
Any suggestions?
While user input is generally better handled by reading input with fgets and then parsing what you need from the resulting buffer with sscanf of simply with a pair of pointers and "inch-worming down" (a/k/a "walking") the string testing each char and handling as needed -- it is always worth a look at scanf to detail what you need to do to successfully use it for user input.
While fgets is not without needed validations, the number and types of validations needed with scanf and handling of characters that remain in the input buffer in the different cases of input failure or matching failures create a number of extra pitfalls for new (and not so new) C programmers.
The two primary problems with scanf are (1) there is no default limitation on the number of characters that it will read into any buffer (potentially overflowing your array); and (2) the fact that it does not remove the trailing '\n' (or any of the characters following an input or matching failure) from the input buffer (e.g. stdin). It is up to you to account for all characters in the input buffer and empty the buffer as needed.
Further complicating the picture are the ways the different scanf format specifiers handle leading-whitespace (numeric conversions typically skip leading whitespace, while a character conversion won't) Another issue is handling included whitespace. The "%s" format specifier will only read up to the first whitespace encountered, making it impossible to read "My dog has fleas" with a single %s specifier. (you can use a character class to read included whitespace -- as shown in the example below)
There are many other subtleties with scanf as well, so it is well worth the time it takes to read and understand man scanf.
From the comments, you now know if you ask for a string of 100 chars, you need, at minimum, 101 characters of storage -- we will assume that is learned.
When taking any input with scanf, you must always validate the return to insure that the number of conversion expected, in fact took place. For example, if you are reading "5 dogs" with the conversion specifier "%d %s", a return of 2 indicates a successful conversion to integer and string. However, you also know, at minimum a '\n' remains in the input buffer (and potentially many more characters, if say, "5 dogs and cats" were entered. It is up to you to remove the '\n' and any other characters that remain, before attempting to read more input with scanf.
The following example captures most of the pitfalls with your example and provides a couple of tools you can use when dealing with user input. The bottom line is learn to use fgets, but know how to use scanf as well. Your goal is to provide as robust and bullet-proof input routine as you can. Think about all the dumb things a user might do when prompted for input (or heaven forbid, a cat walks across the keyboard) There are always more validations you can add. Look at each of the included validations, and let me know if you have questions:
#include <stdio.h>
#include <string.h>
#define MAXC 100 /* if you need a constant, declare one */
/* helper function to remove any chars left in input buffer */
void empty_stdin()
{
int c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
}
int main (void) {
char str1[MAXC+1] = ""; /* initialize to all zero */
int index, rtn, len; /* index, return, length */
for (;;) { /* loop until valid input obtained */
printf ("Enter text of max 100 characters: ");
rtn = scanf ("%100[^\n]", str1); /* read at most MAXC char */
if (rtn != 1) { /* validate scanf return */
if (rtn == EOF) { /* check if EOF, ctrl+d, ctrl+z (windoze) */
printf ("input canceled.\n");
return 0;
}
if (!str1[0]) /* was a character entered? */
fprintf (stderr, "error: string is empty.\n");
/* remove '\n' and any chars that remain in stdin */
empty_stdin();
}
else { /* all conditions met, good entry, empty stdin and break */
empty_stdin();
break;
}
}
len = (int)strlen (str1); /* get string length */
for (;;) { /* now do the same thing for integer */
printf ("Enter the index to search (0-%d): ", len - 1);
if ((rtn = scanf ("%d", &index)) != 1) {
if (rtn == EOF) {
printf ("input canceled.\n");
return 0;
}
fprintf (stderr, "error: invalid input - not integer.\n");
/* only need to strip if non-integer entered, because %d
* will skip leading whitespace, including '\n'.
*/
empty_stdin();
}
else if (index < 0 || len < index + 1) /* validate index value */
fprintf (stderr, "error: invalid index - out of range.\n");
else
break;
}
printf ("your char is: %c\n", str1[index]);
return 0;
}
Example Use/Output
$ ./bin/scanfstr1
Enter text of max 100 characters: 12345678901234567890
Enter the index to search (0-19): -1
error: invalid index - out of range.
Enter the index to search (0-19): 0
your char is: 1
$ ./bin/scanfstr1
Enter text of max 100 characters: 12345678901234567890
Enter the index to search (0-19): foo
error: invalid input - not integer.
Enter the index to search (0-19): 6
your char is: 7
$ ./bin/scanfstr1
Enter text of max 100 characters: My dog has fleas.
Enter the index to search (0-16): d
error: invalid input - not integer.
Enter the index to search (0-16): 3
your char is: d
$ ./bin/scanfstr1
Enter text of max 100 characters:
error: string is empty.
Enter text of max 100 characters: My cats are fine.
Enter the index to search (0-16): meow
error: invalid input - not integer.
Enter the index to search (0-16): input canceled.