I'm going through an introduction to programming in C book and I'm not sure what a line of code is doing. I run the code with and without this statement, the result is the same. I suspect that it is getting rid of the 'Enter' after the user inputs a string, but am not sure. I'm assuming the authors wrote this line for a reason. The character array is passed to a function that loops through an array of arrays and finds the text to search for using the 'strstr function.
int main () {
char search_for[80];
printf("Enter text to search for: ");
scanf("%79s", search_for);
search_for[strlen(search_for) -1] = '\0'; // why is this line here?
find_track(search_for);
return 0;
}
It overwrites the last character of the the scanned string with a null character, shortening the string by one character. Why the programmer wanted to do such a thing I can't say.
It's a mistake. That code was written to be used with fgets not scanf. Fgets adds a newline char to the end of the string the user enters and "search_for[strlen(search_for) -1] = '\0' " would overwrite that newline char with '\0'.
The problem: The code above with scanf causes the last character the user enters to be overwritten. So, a search using the string "ab" would only search for "a".
The program will work properly if "search_for[strlen(search_for) -1] = '\0'" is not included.
Delete one character from the end of the "string" search_for.
Related
I am a beginner of C and trying to extract Characters from standard input.
Input = "C0h1r2i3s4"
Expected Outcome = "Chris"
I've tried two ways to achieve this:
Use scanf to store input in one variable -> traverse through input one character a time -> if that character is not a number in ASCII table, store that character in a variable
Use fgets to get input and store in one variable -> traverse through input one character a time -> if that character is not a number in ASCII table, store character in a variable
I wonder if it's possible to use scanf/fgets to get only the characters from stdin? So that I don't have to traverse through every characters.
I've tried to use scanset below, but it seems scanf always screens at character-level and stops when the next char does not fit specified format.
Anyway, I wonder if there is a more powerful use of scanset & scanf.
Code for scanf()
#include <stdio.h>
#include <stdlib.h>
void main()
{
char str[50];
//intput = C0h1r2i3s4
scanf("%s", &str); // str = "C0h1r2i3s4"
//intput = C0h1r2i3s4
scanf("%*c%*d%s", &str); // str = "h1r2i3s4" -> C & 0 is ignored
//intput = C0h1r2i3s4
scanf("%[A-Z,a-z]%*d%s", &str); // str = "C" -> are they a valid format identifier? "%[A-Z,a-z]%*d%s"
}
Just want to close this question in case someone else is looking for similar one
In C, there is no simple way to extract certain characters directly from stdin.
first, we need to read the complete inputs from stadin
then, we travers through the inputs to decides which characters are in concern
Thank you, the-busybee, for your comment that saved my life earlier this year. I cannot add a comment due to not enough reputation on GitHub, and I just realized that I could reply to my own post.
So I need to solve a problem where I have to read words from a file and still be able to recognize if a word is at the end of a line. For example:
This is a test file
I need to distinguish every word
and still be able to print out every words that are at the end of a line
I tried using:
while(scanf("%s", string) != EOF){
len = strlen(string);
if (string[len] == '\n'){
printf("%s is a word at the end of a line", string);
}
}
but nothing seems to be properly working.
Can somebody help me?
Edit 1: I have tried
if (string[len-1] == '\n')
but it gives the last character of the word instead. For example the word string[len-1] of "file" is 'e' even though it's the word that's at the end of line 1
Your scanf call reads words, returning one each time. It skips over both spaces and newlines, so there is no way you can look at one of the words to see if it was at the end of a line. You need a different approach.
Try using scanf("%[^\n]") instead of %s so you can read until end of line, after that, you read your string from end to first space to get the last word
Why does the second strncpy give incorrect weird symbols when printing?
Do I need something like fflush(stdin) ?
Note that I used scanf("%s",aString); to read an entire string, the input that is entered starts first off with a space so that it works correctly.
void stringMagic(char str[], int index1, int index2)
{
char part1[40],part2[40];
strncpy(part1,&str[0],index1);
part1[sizeof(part1)-1] = '\0';//strncpy doesn't always put '\0' where it should
printf("\n%s\n",part1);
strncpy(part2,&str[index1+1],(index2-index1));
part2[sizeof(part2)-1] = '\0';
printf("\n%s\n",part2);
}
EDIT
The problem seems to lie in
scanf("%s",aString);
because when I use printf("\n%s",aString); and I have entered something like "Enough with the hello world" I only get as output "Enough" because of the '\0'.
How can I correctly input the entire sentence with whitespace stored? Reading characters?
Now I use: fgets (aString, 100, stdin);
(Reading string from input with space character?)
In order to print a char sequence correctly using %s it needs to be null-terminated. In addition the terminating symbol should be immediately after the last symbol to be printed. However this section in your code: part2[sizeof(part2)-1] = '\0'; always sets the 39th cell of part2 to be the 0 character. Note that sizeof(part2) will always return the memory size allocated for part2 which in this case is 40. The value of this function does not depend on the contents of part2.
What you should do instead is to set the (index2-index1) character in part2 to 0. You know you've copied that many characters to part2, so you know what is the expected length of the resulting string.
I have been struggling to figure out the fscanf formatting. I just want to read in a file of words delimited by spaces. And I want to discard any strings that contain non-alphabetic characters.
char temp_text[100];
while(fscanf(fcorpus, "%101[a-zA-Z]s", temp_text) == 1) {
printf("%s\n", temp_text);
}
I've tried the above code both with and without the 's'. I read in another stackoverflow thread that the s when used like that will be interpreted as a literal 's' and not as a string. Either way - when I include the s and when I do not include the s - I can only get the first word from the file I am reading through to print out.
The %[ scan specifier does not skip leading spaces. Either add a space before it or at the end in place of your s. Also you have your 100 and 101 backwards and thus a serious buffer overflow bug.
The s isn't needed.
Here are a few things to try:
Print out the return value from fscanf, and make sure it is 1.
Make sure that the fscanf is consuming the whitespace by using fgetc to get the next character and printing it out.
writing another program, it reads a txt file, and stores all the letter characters and spaces (as \0) in a char array, and ignores everything else. this part works.
now what i need it to do is read a user inputted string, and search for that string in the array, then print the word every time it appears. im terrible at I/O in C, how do you read a string then find it in a char array?
#include <stdio.h>
...
char str [80];
printf ("Enter your word: ");
scanf ("%s",str);
char* pch=strstr(fileData,str);
while (pch!=NULL)
{
printf ("found at %d\n",pch-fileData+1);
pch=strstr(pch+1,str);
}
read in the user inputted string as a char array as well (cause strings are basically char* anyway in C)
use a string matching algorithm like Boyer-Moore or Knutt-Morris-Pratt (more popularly known as KMP) - google for it if you like for C implementations of these - cause they're neat, tried and tested ways of searching strings for substrings and pattern matches and all.
for each of these indexOf cases, print the position where the word is found maybe? or if you prefer, the number of occurrences.
Generally, the list of C string functions, found here, say, are of the format str* or strn*, depending on requirements.
One for-loop inside another for-loop (called nested loop). Go through all the letters in your array, and for each letter go through all the letters in your input string and find out if that part of the array matches with the input string. If it does, print it.