I am close to finish writing a program to swap two words inputed to a program. If i input "Billy Bob" the output will be "#\300_\377" Something weird like that... I believe there is something wrong with my scanf but not quite sure. Here is what i have so far..
{ int i,j,l;
char str[59];
printf("Enter the string\n");
scanf("%s", &str[59]);
l=strlen(str);
for(i=l-1; i>=0; i--)
{ if(str[i]==' ')
{ for(j=i+1; j<l; j++)
printf("%c",str[j]);
printf(" ");
l=i;
}
if(i==0)
{ printf(" ");
for(j=0; j<l; j++)
printf("%c",str[j]);
}
}
scanf("%s", &str[59]);
Writes the input at the end of the allocated space. Use the address of the first element:
scanf("%s", str);
but this will give you the first word, so either do:
scanf("%s %s", str1, str2); // str1, str2 are arrays
or use fgets:
fgets(str, 59, stdin);
Instead of using scanf("%s", &str[59]);, you could use gets(str);.
It works perfectly fine...
This is wrong:
scanf("%s", &str[59]);
//^not reading the str, str[59] is even out of bound
should be:
scanf("%s", str);
That way of writing the function is somewhat difficult to read. I'm not exactly sure what circumstances you are writing it in but an alternative solution would be to split up the input string by a token, in this case a space, and print out the two strings in the opposite order. An example of the function strtok() can be found here.
Something like this:
char str[] ="billy bob";
char * firstToken;
char * secondToken
firstToken = strtok(str, " ");
secondToken = strtok(NULL, " ");
printf("%s %s", secondToken, firstToken);
You're passing the first address after str to scanf. Change &str[59] to str.
Related
I have this code:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
This gets a string with the possibility of having spaces and assigns it to the variable variable1. Later, I can print the string with no problem.
The problem comes when I add to code other fgetsfor gets other string in other variable.
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
The result complete is:
char temp;
scanf("%c",&temp);
fgets(variable1,50,stdin);
strtok(variable1, "\n");
printf("%s ", variable1);
if (1) {
scanf("%c",&temp);
fgets(variable2,50,stdin);
strtok(variable2, "\n");
printf("%s ", variable2);
}
variable1 always works correctly. But I try print in some phrases with %s variable2 but the result does not get the first character, only in second scanf. If I put HELLO, variable2 is ELLO.
I have tested using another temp variable, another data, etc. But always get the same error.
Why is this happening?
UPDATE
For more information. I use scanf because, if I do not use it, the program does not pause while waiting for the string. I use strtok(variable1, "\n"); to remove the line break.
This program is inside a while and in switch case. I put the complete code:
case 4: printf( "Put equipo: ");
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
}
break;
If I introduce like Equipo HELLO and like Piloto FRIEND, the output is:
You said HELLO and RIEND
Re-written based on OP latest edits to post, and comments...
You describe the need to simply obtain two strings from user input, remove the newlines from each, then package both into a message to stdout. If this description actually matches what you need, change this code section:
...
scanf("%c",&temp);
fgets(equipo,50,stdin);
strtok(equipo, "\n");
if (Exists(equipo)) {
printf("Put Piloto ");
scanf("%c",&temp);
fgets(piloto,50,stdin);
strtok(piloto, "\n");
printf("You said %s and %s", equipo, piloto);
...
To this:
...
printf("enter equipo: ");
if(fgets(equipo, sizeof(equipo), stdin))
{
equipo[strcspn(equipo, "\n")] = 0; //remove newline
printf("enter piloto: ");
if(fgets(piloto, sizeof(piloto), stdin))
{
piloto[strcspn(piloto, "\n")] = 0;
printf("You said %s and %s", equipo, piloto);
}
}
...
Note: strtok(piloto, "\n"); works, but has problems if user just hits <return>
By the way, here are some other interesting ways to clear the newline
I do not understand your example code. Could you update the question with your actual code?
I assume scanf should not be there?
This code works fine for me:
char var1[50], var2[50];
fgets(var1, 50, stdin);
strtok(var1, "\n");
printf("Var1: %s\n", var1);
if (1) {
fgets(var2, 50, stdin);
strtok(var2, "\n");
printf("Var2 %s\n", var2);
}
Output:
Test1
Var1: Test1
Test2
Var2 Test2
My assignment is to write a function that takes an input string from a user, tokenize it into several strings each containing an individual word from the input sentence, and then reverses the sentence. The result will be the sentence input but with the words in the reverse order.
For now, I just have the function taking in the input, tokenizing it into individual words, storing those words into an array, and printing out each individual word in order. I do not have the process for reversing the order of the words written yet.
Here is the code for the function i have handling this so far:
void reverse(void){
printf("\n\n%s\n", "Reverse words in String: ");
char input[200];
printf("\n%s", "Enter string\n> ");
scanf("%s", &input);
char reverseSentence[200];
char sentenceParts[20][200];
int wordCount = 0;
char *thisWord = strtok(input, " ");
strcpy(sentenceParts[wordCount], thisWord);
wordCount++;
while(thisWord != NULL){
thisWord = strtok(NULL, " ");
strcpy(sentenceParts[wordCount], thisWord);
wordCount++;
}
printf("\n\n");
for(int i = 0; i < wordCount + 1; ++i){
printf("%s%s", sentenceParts[i], " ");
}
}
The problem lies in the while statement:
while(thisWord != NULL){
thisWord = strtok(NULL, " ");
strcpy(sentenceParts[wordCount], thisWord);
wordCount++;
}
The program exits with a segmentation fault error at the strcpy statement. I cannot understand for the life of me why it is doing this. It seems like it worked just fine outside of the while loop.
Any thoughts? I've been stuck on this for quite a bit now and can't find too many other resources out there to help.
Updating thisWord with the next token should happen at the end of the loop body. As is, you'll eventually update thisWord with a NULL, and then call strcpy with a NULL. And that is your segfault.
So the loop should look like this:
char *thisWord = strtok(input, " ");
while(thisWord != NULL){
strcpy(sentenceParts[wordCount], thisWord);
wordCount++;
thisWord = strtok(NULL, " ");
}
The other problem (pointed out by #WhozCraig in the comments) is that you are inputting the line using scanf("%s", ...). That doesn't work because scanf will stop at the first whitespace character. Hence, you'll only get one word at a time from scanf. To get an entire line, use the fgets function.
I am very new to c programming, and for a school assignment I need to write a programm that takes a string as input and add the letters “ay” to each word that starts with a consonant at the front of this word. It is hinted that this should be done with strncpy and strcat.
this is the code that I wrote:
#include <stdio.h>
#include <string.h>
int main()
{
char myString[50];
char abc[26] = "bcdfghjklmnpqrstvwxyz";
char strA[50];
char strB[50];
char strC[150];
char ay[3] = "ay";
printf("** Welcome to the Double Dutch game **\nPlease enter a string: ");
scanf(" %[^\n]s", &myString);
int i, j;
for (i=0; myString[i]!='0'; i++) {
for(j=0; abc[j]!='\0'; j++) {
if(abc[j] == myString[i]){
if(myString[i-1] == ' '){
strncpy(strC, &myString[0], i);
strncpy(strB, &myString[i], 40);
strcat(strC, ay);
strcat(strC, strB);
myString[0] = '\0';
strcat(myString, strC);
strC[0] = '\0';
strB[0] = '\0';
}
}
}
}
printf("Result: %s", myString);
}
When i run this code it keeps giving the error * Buffer overlow detected *: /home/a.out terminated. I cannot find the mistake that I made. Hopefully someone can help me.
Thanks
Change this:
scanf(" %[^\n]s", &myString);
to this:
scanf(" %[^\n]", myString);
since %[^\n] conversion modifier is not a modifier for %s, they are independent. As a result, you can discard it.
Tip: Add the size of your array - 1, to prevent a possible buffer overflow, like this: scanf(" %49[^\n]", myString);
I can't work out why Strchr() is not working in my function. I need to see if the users guess matches any of the letters in a hidden word. It is a Hangman game.
int guessLetter(char* word, int* guessedLetters)
{
char guess[20];
char *s;
printf("Enter your guess: ");
scanf("%s", &guess);
s = strchr (word, guess);
printf("%s", s);
if (s != NULL) {
printf ("Good Guess\n");
} else {
printf ("Bad Guess\n");
}
}
No matter if the guess is right or wrong, my else statement is being activated. My printf shows that s is being given the value of Null no matter if the character is in the word or not.
So I guess my problem is with this part of the code:
s = strchr (word, guess);
I am new to C, so I am sure I am just missing something very basic. I have tried to search the web as much as I can, but I don't really seem to be able to understand what I am doing wrong.
strchr takes an int as 2nd argument but you are passing a char*. You Turn on your compiler warnings.
What you wanted is to loop over the word to see if any of the characters are in guess.
s = 0;
for(size_t i=0; word[i]; i++) {
s = strchr (guess, word[i]);
if(s) break; //Found a match
}
This would break on the first match and you can modify it if you want to check for all characters in word.
There's an argument mismatch in scanf call too:
scanf("%s", &guess);
should be
scanf("%s", guess);
scanf expects a char* for format string %s but you are passing char(*)[20] i.e. &guess is of type char (*)[20].
Does it not return an int or something?
This is a snippet of my code:
int wordlength(char *x);
int main()
{
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
printf("Word Length: %d", wordlength(word));
return 0;
}
int wordlength(char *x)
{
int length = strlen(x);
return length;
}
Function strlen is applied to strings (character arrays) that have the terminating zero. You are applying the function to a pointer to a single character. So the program has undefined behaviour.
Change this part:
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
to:
char word[256]; // you need a string here, not just a single character
printf("Enter a word: \n");
scanf("%255s", word); // to read a string with scanf you need %s, not %c.
// Note also that you don't need an & for a string,
// and note that %255s prevents buffer overflow if
// the input string is too long.
You should also know that the compiler would have helped you with most of these problems if you had enabled warnings (e.g. gcc -Wall ...)
Update: For a sentence (i.e. a string including white space) you would need to use fgets:
char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);