I have a binary search function that will search for a word in an array, but before I can search the array I need to know what word to search for. I have written the code to ask the user for input, but the program prints out the request for input but doesn't accept anything from the user. I was thinking it was a buffer issue, as I have an initial scanf in the program that loads all the character strings from an external file and places them in an array. I have tried using fflush after my initial scanf, and I tried rewriting the second one with gets, as pointed out in previous threads. Perhaps I am not implementing it correctly. Here's what I have so far, any tips as to why the second scanf isn't working is appreciated.
#include "set.h"
#include "sortAndSearch.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char names[320][30];
char str[30];
int i, j;
char *key;
int numOfWords;
char userWord[30];
Set set1, set2, set3;
//scan each char string into array names
for(i=0; scanf("%s", str) != EOF; i++){
strcpy(names[i], str);
}
//set number of words in file
numOfWords = i;
//sort names array
//bubbleSort(names, numOfWords);
//print out names, sorted
//for(i=0; i<numOfWords; i++){
// printf("%s\n", names[i]);
//}
printf("What word would you like to search for? ");
scanf("%s", userWord);
//addName2Set(set1, userWord);
return 0;
}
Your second scanf doesn't work because your first scanf never terminates. scanf won't return EOF unless the input stream is closed - that would be that the console closes.
Since scanf returns the number of characters read you should instead make your loop condition scanf(%s, str) != 0. That will make the loop end as soon as the user hits enter without entering anything.
Your initial scanf() in a loop read everything up to EOF, so there's nothing left for the 'What word would you like to search for?' scanf() to read.
One way around this problem is to read the initial names from a file (fopen(), fscanf(), fclose() — and the file name might be an argument to the program, or a fixed name).
Another way you could try is clearerr(stdin); before the 'What word' scanf(). That (clearerr()) unsets the EOF bit and allows scanf() to try again. It may work if the input of the program is the terminal; it won't help if the input of the program is coming from a file.
int main(int argc, char **argv)
{
char names[320][30];
char str[30];
int i, j;
char *key;
int numOfWords;
char userWord[30];
Set set1, set2, set3;
FILE *fp;
if (argc != 2)
{
fprintf(stderr, "Usage: %s word-file\n", argv[0]);
exit(1);
}
if ((fp = fopen(argv[1], "r")) == 0)
{
fprintf(stderr, "Usage: %s word-file\n", argv[0]);
exit(1);
}
//scan each char string into array names
for (i = 0; i < 320 && fscanf(fp, "%29s", str) != EOF; i++)
{
strcpy(names[i], str);
}
fclose(fp);
//set number of words in file
numOfWords = i;
This insists that you use ./a.out example.dat (instead of ./a.out < example.dat). It will then work more or less as you want it to. Of course, the code for reading the file should be in a function that is passed the file name, the array, and the array size. The 320 in the loop is overflow protection and should be an enumeration enum { MAX_WORDS = 320 }; that's used both in the array declaration and the loop. The 29 is overflow protection; it is hard to parameterize that, but it is one less than the second dimension of the array.
Your question and code seemed awfully misaligned at first glance...
scanf() is the wrong function for reading from your file, you want fscanf(), or if the file is formatted such that each word is on its own line fgets() works too (newline stops reading of each string). Likewise, you can use gets() instead of scanf() to read user input if the input is just a string followed by return(newline).
Everything you need to know about stdio.h
Related
I must write a program in C that can print the middle letter of the string you entered. Spaces () are also calculated, and the number of characters must be odd.
Ex. Input
Hi sussie
--> 9 characters, including space
The output should be s.
I have tried this:
#include <stdio.h>
#include<string.h>
char x[100];
int main(void)
{
printf("Hello World\n");
scanf("%c\n",&x);
long int i = (strlen(x)-1)/2;
printf("the middle letter of the word is %c\n",x[i]);
return 0;
}
and the output always shows the first letter of the word I have entered.
You're only reading the first character from stdin (and incorrectly; you shouldn't be using &).
If you must use scanf, you should use this format:
scanf("%99[^\n]", x);
This is safe and doesn't read past the buffer.
Note that %s wouldn't work here. %s causes scanf to interpret whitespace as the end of the string.
A much better, safer, and easier solution would be to use fgets instead of scanf; fgets is safer and it doesn't require you to change a format string when you change the size of your array:
fgets(x, sizeof(x)-1, stdin);
This eliminates any possible issues with whitespace or buffer overflow.
int main()
{
char arr[1024];
char a;
int i,counter=0;
printf("enter string :: ");
fgets(arr,sizeof(arr),stdin);
for(i=0;i<strlen(arr);i++)
counter++;
for(i=0;i<strlen(arr);i++)
{
if(i==(counter/2))
printf("%c\n",arr[i]);
}
return 0;
}
i am new in c. So in my university, i just learn about file in c. and i got a task. If i put an empty file in my project directory, and read it. The output are symbols (i dont know what symbol it is). So here is the code, please help
player dota[100];
FILE *fp;
fp = fopen("soal09.txt", "r");
if(fp == NULL)
{
printf("Error Opening The File!!\n");
return 0;
}
else
{
while(!feof(fp))
{
fscanf(fp, "%[^ ] %d %d\n", &dota[idx].name, &dota[idx].score, &dota[idx].num);
idx++;
}
}
fclose(fp);
do
{
enter();
menu();
printf("Input your choice [1..5]: ");
scanf("%d", &choose); fflush(stdin);
if(choose == 1)
{
system("cls");
enter();
printf("%-20s %-15s %s\n", "Player Name", ": Average Score", ": Number of Playing");
printf("====================================================================\n");
for(int i = 0; i < idx; i++)
{
printf("%-20s %-15d %d\n", dota[i].name, dota[i].score, dota[i].num);
}
printf("\nPress Enter to Continue...");
getchar();
}
getchar();
return 0;
}
and the output is ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ -858993460
Thank you ^^
The end-of-file indicator that is checked by feof() is only set after a previous file I/O operation has failed. You must attempt an I/O operation to find out if you have reached the end of the file. So, with an empty file, your code attempts to read the file, the end-of-file indicator is set, no values are read into the first struct, but idx is incremented, so it looks like you have added data for a player. But the fields of the first struct are uninitialized, so you are seeing garbage. Also note that dota[idx].name is presumably an array of chars, so it decays to a pointer to char when passed to fscanf(). Using &dota[idx].name, as you have, is wrong, though it might appear to work. It does cause the compiler to emit a warning, and you should have these enabled (I always use at least gcc -Wall -Wextra -pedantic).
You should not use feof() to control file I/O loops. One simple solution is to use the return value of fscanf() to control the loop:
while(fscanf(fp, "%[^ ] %d %d\n",
dota[idx].name, &dota[idx].score, &dota[idx].num) == 3) {
idx++;
}
This will only update a player struct if three assignments are made by the call to fscanf(). But, the problem with this simple solution is that it doesn't handle malformed input well. If a line of the data file is missing a field, the struct will be incorrectly filled, and the loop will terminate, even if there are more lines in the file to read. Also, since no field width is specified for the string conversion, a long name could crash your program.
A better solution uses fgets() to read the lines of the file into a buffer, and then uses sscanf() to extract the information from the buffer:
#include <string.h> // for strcpy()
...
char buffer[1000];
int line = 0;
char temp_name[100];
int temp_score, temp_num;
while(fgets(buffer, sizeof(buffer), fp)) {
++line;
if (sscanf(buffer, "%99[^ ] %d %d\n",
temp_name, &temp_score, &temp_num) == 3) {
strcpy(dota[idx].name, temp_name);
dota[idx].score = temp_score;
dota[idx].num = temp_num;
++idx;
} else if (buffer[0] != '\n') {
fprintf(stderr, "Bad input in line %d\n", line);
}
}
Here, a generous buffer is declared to accept a line of text from the file, and temporary variables are declared to hold the values to be stored in the struct fields. I have chosen a size of 100 for temp_name, but this should match the size of the string array in your actual struct. Note that the string conversion in sscanf() has a field width of 99, so that at most 99 non-space (not non-whitespace, and why aren't you just using %99s here?) characters are matched, leaving space for the '\0' to be added.
fgets() will return NULL when it reaches the end of the file, so the loop will continue until that happens. For each line that is read, a line counter is incremented. Then sscanf() is used to read data into the temporary variables. The value returned from sscanf() is checked to be sure that 3 assignments were made, and if so, then the data is copied into the struct, and idx is incremented. Note that strcpy() is needed to copy the string from temp_name to dota[idx].name.
If the value returned from sscanf() indicates that something other than 3 assignments were made, there is a check to see if buffer holds an empty line. If not, an error message is printed to stderr providing the line number of the bad input in the file.
A couple of further comments. Your do loop appears to be missing the associated while(). And you use fflush(stdin) after the scanf() inside the do loop. fflush()is meant to flush output streams. The behavior of fflush() on input streams is explicitly undefined in the C Standard (ISO/IEC 9899:2011 7.21.5.2/2), though I believe that Microsoft deviates from the Standard here. Nevertheless, you should not use fflush(stdin) in portable C code. Instead, use something like this:
int c;
...
scanf("%d", &choose);
while ((c = getchar()) != '\n' && c != EOF)
continue; // discard extra characters
This code reads characters from the input stream until either a '\n' or EOF is reached, clearing any characters left behind by the previous call to scanf() from the input stream.
I'm trying to ask the user to type in a string so I will print the length of the string. My code is built succeeded. However, when I entered a word and pressed 'enter', the program keeps running. I had to enter a second word, then the length of the first string displays. I'm confused at argv[1]. Can someone give me some tips and hint on how to fix this? Thanks in advance for your time.
Please note that I'm not allowed to use any string function.
int main(int argc, char* argv[]){
char* s=argv[1];
char input[256];
s = input;
printf("Please enter a string: ");
scanf("%s\n", s);
int str_length = 0;
while (s[str_length] != '\0')
{
str_length++;
if (s[str_length] == '\0') break;
}
printf("%d\n", str_length);
return 0;
}
argv[] is the array that holds your command line parameters, argv[1] is the first one (other than the command representation itself in argv[0], of course). You assign it to s then immediately overwrite s, so it's not really needed here.
The reason you're having to enter two lines is the \n at the end of your input format. It requires whatever can match the format string followed by a newline, hence the %s\n is eating your first newline so that scanf has to go back for another one.
%s on it's own will fix that problem but introduce another one if what you're after is a full line of input - it will only read up to the first whitespace. For a proper line input function, see here.
It does full line input with protection against buffer overflows and detection/cleanup of lines that were too long, something sorely missing in the scanf("%s") input method.
In addition, the if statement within the while is superfluous here since the while itself will catch the end of the string, and it makes little sense to have both input and s refer to the same array (it would make sense if you changed s at some point, but that's not happening here).
So, a variant without the advanced line iput function could be as simple as:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char* argv[]) {
char input[256];
int str_length = 0;
printf ("Please enter a string: ");
scanf ("%s", input);
while (input[str_length] != '\0') /* Or consider using strlen() */
str_length++;
printf ("%d\n", str_length);
return 0;
}
If you enter Hello, you'll see that it prints out 5 immediately. You'll also see 5 if you enter Hello Pax, which is one reason to choose the advanced input function (the other, very important, reason is to avoid introducing a buffer overflow vulnerability into your program).
argv is used to pass process arguments. this means you can run your program like
a.out 123 abcd
argv[1] will already be assigned to a value of 123. you do not have to read it as you are doing now. in your current code , you are overwriting the reference of s to a new string after assigning it with argv[1].
This is what you want
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX 100
int main(int argc, char* argv[]){
char tmp[MAX];
printf("Plese enter a string:\n");
scanf("%s", tmp);
printf("the length is %d\n", strlen(tmp));
return 0;
}
The argv and argc is another thing like this:
argv[0] = a.exe
argv[1] = 12345
int main(int argc, char* argv[]){
printf("the length is %d\n", strlen(argv[1]));
return 0;
}
/*-------------------- Output --------------------
> a.out 12345
the length is 5
------------------------------------------------*/
Just change the scanf line:
scanf("%s", s);
As you have it (scanf("%s\n", s);), it requires a sequnce of characters ending in \n, then another \n to indicate when the input is finished.
This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 4 years ago.
I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE.
What I'm trying to do is reading a string (like "Barack Obama") and put it in a variable:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Your Name is: %s", name);
return 0;
}
Output:
Enter your name: Barack Obama
Your Name is: Barack
How can I make the program read the whole name?
Use:
fgets (name, 100, stdin);
100 is the max length of the buffer. You should adjust it as per your need.
Use:
scanf ("%[^\n]%*c", name);
The [] is the scanset character. [^\n] tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer (which is not read), and the * indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.
Read here about the scanset and the assignment suppression operators.
Note you can also use gets but ....
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
Try this:
scanf("%[^\n]s",name);
\n just sets the delimiter for the scanned string.
Here is an example of how you can get input containing spaces by using the fgets function.
#include <stdio.h>
int main()
{
char name[100];
printf("Enter your name: ");
fgets(name, 100, stdin);
printf("Your Name is: %s", name);
return 0;
}
scanf(" %[^\t\n]s",&str);
str is the variable in which you are getting the string from.
The correct answer is this:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
// pay attention to the space in front of the %
//that do all the trick
scanf(" %[^\n]s", name);
printf("Your Name is: %s", name);
return 0;
}
That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.
NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.
#include<stdio.h>
int main()
{
int i,size;
char a[100];
fgets(a,100,stdin);;
size = strlen(a);
a[size-1]='\0';
return 0;
}
Update: Updated with help from other users.
#include <stdio.h>
// read a line into str, return length
int read_line(char str[]) {
int c, i=0;
c = getchar();
while (c != '\n' && c != EOF) {
str[i] = c;
c = getchar();
i++;
}
str[i] = '\0';
return i;
}
Using this code you can take input till pressing enter of your keyboard.
char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
scanf("%c ", &ch[i]);
}
While the above mentioned methods do work, but each one has it's own kind of problems.
You can use getline() or getdelim(), if you are using posix supported platform.
If you are using windows and minigw as your compiler, then it should be available.
getline() is defined as :
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
In order to take input, first you need to create a pointer to char type.
#include <stdio.h>
#include<stdlib.h>
// s is a pointer to char type.
char *s;
// size is of size_t type, this number varies based on your guess of
// how long the input is, even if the number is small, it isn't going
// to be a problem
size_t size = 10;
int main(){
// allocate s with the necessary memory needed, +1 is added
// as its input also contains, /n character at the end.
s = (char *)malloc(size+1);
getline(&s,&size,stdin);
printf("%s",s);
return 0;
}
Sample Input:Hello world to the world!
Output:Hello world to the world!\n
One thing to notice here is, even though allocated memory for s is 11 bytes,
where as input size is 26 bytes, getline reallocates s using realloc().
So it doesn't matter how long your input is.
size is updated with no.of bytes read, as per above sample input size will be 27.
getline() also considers \n as input.So your 's' will hold '\n' at the end.
There is also more generic version of getline(), which is getdelim(), which takes one more extra argument, that is delimiter.
getdelim() is defined as:
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
Linux man page
If you need to read more than one line, need to clear buffer. Example:
int n;
scanf("%d", &n);
char str[1001];
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",str);
"%s" will read the input until whitespace is reached.
gets might be a good place to start if you want to read a line (i.e. all characters including whitespace until a newline character is reached).
"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;
#include <stdio.h>
int main()
{
printf("Enter your name\n");
char a[80];
gets(a);
printf("Your name is %s\n", a);
return 0;
}
scanf("%s",name);
use & with scanf input
int main(void) {
char *input;
printf("prompt>");
scanf("%s", input);
printf("%s", input);
return 0;
}
prompt>input
RUN FAILED (exit value 138, total time: 3s)
What's wrong with the code? Has to be either the scanf() or the second printf(). The input is of unknown length. A lot people have said to simply create a char array of length 'X' to hold the input. Just wanted to know then why this code works.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* prompt */
char input;
printf("prompt>");
scanf("%s", &input);
printf("%s", &input);
return 0;
}
Your specific problem is that you have no storage behind input. It's an uninitialised pointer, pointing to a random spot in memory, which is unlikely to be anywhere useful.
You can use something like:
char *input = malloc (100);
// check that input != NULL
// use it
free (input);
or:
char input[100];
but you have a serious problem with your use of scanf (see below).
You should never use an unbounded %s in scanf (or any of its variants unless you totally control the input). It's a dangerous practice prone to buffer overflows and the sooner you get out of the habit, the better. It's akin to gets() in that way.
From an earlier answer of mine, this piece of code below (along with your main code incorporated into it) provides a safe way of getting user input. You pass in an optional prompt, the buffer to load the input into, and the size of the buffer.
It will return the input up to the size of the buffer (stripped of the newline if there) then clear out the rest of the line if necessary so that it doesn't affect the next input operation. It will return either OK or an error indication on end-of-file or if the input was too long (you still get the first part of the input in case you want to do something with it).
Once you have the line, you can sscanf it, safely, to your heart's content. However, that's not required in your case since you're only trying to get a string. Just use the buffer that's returned directly.
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
int main(void) {
char input[10];
int rc = getLine ("prompt> ", input, sizeof (input));
switch (rc) {
case NO_INPUT: printf ("\nNo input recieved\n"); break;
case TOO_LONG: printf ("Too long, truncated input below:\n");
default: printf("Your input was [%s]\n", input);
}
return 0;
}
Give that a shot, it's far more robust than using scanf("%s") on its own.
As for your update asking why this works:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* prompt */
char input;
printf("prompt>");
scanf("%s", &input);
printf("%s", &input);
return 0;
}
It's undefined code. Period. You only allocate space for a character but you scan in a string. Since a string is a character array of all the characters followed by a zero character, the only string you could input safely there would be an empty one.
Anything else will write to both the character and whatever happens to be adjacent to the character on the stack.
This is no different to allocating char input[100] then entering 200 characters, it's still buffer overflow and should be avoided.
Discussion below is based on a particular implementation of C, not necessarily all implementations.
Chances are, you got lucky here. Compilers may generate code that keeps the stack pointer aligned so that, even though you asked for one byte, you may get space allocated for four (or even more, depending on the architecture - I'll assume most types are four bytes here for simplicity).
In addition, you may find that you can also safely overwrite the eight bytes of argc integer and argv pointer (they're probably still there even though you don't use them, no point having two different sets of start-up code just to save a few bytes on the stack).
If you write further than that, you'll eventually overwrite the return address from main to your start-up code. Then you'll know about it since your code will go off into la-la land when main exits.
With undefined behaviour, anything can happen. Sometimes that anything includes the possibility that it will work perfectly (similar to "throw a deck of cards in the air often enough and they'll eventually fall in a nice neat sorted heap" but a little less random).
That does not make undefined behaviour any less of a bad thing.
char *input;
Is only a pointer - there is no data space allocated store the data that scanf collects.
try this instead
char input[100];
You may want to try scanf("%c", input) inside of a while loop that has your delimiting character. You should also make input an array char input[X] where X is a number of sufficient value to hold the most likely values for your input. I would try making input an array first though.
You forgot to allocate the memory before using your pointer.
Try it:
int main(void) {
char input[256];
printf("prompt>");
scanf("%s", input);
printf("%s", input);
return 0;
}
or even:
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char *input = (char *) malloc(sizeof(char) * 256));
printf("prompt>");
scanf("%s", input);
printf("%s", input);
return 0;
}
What compiler do you use? In Turbo C 3.0 it works.
Try this variant:
#include <stdio.h>
#include <alloc.h>
int main(void)
{
char *input = (char*)calloc(100, sizeof(char));
printf("prompt>");
scanf("%s", input);
printf("%s", input);
free(input);
return 0;
}
Try:-
int main(void) {
char input[100];
printf("prompt>");
scanf("%99s", input);
printf("%s", input);
return 0;
}
This will limit the string to 99 bytes. Note "%s" == string of characters delimited by white space or newline ie. you only get the first word!
I think what you really want is:
#include <stdio.h>
int main(void) {
char input[99];
printf("prompt>");
fgets(input,99,stdin);
printf("->%s<-", input);
return 0;
}
You probably need to add some code to get rid of unwanted new line characters!