the assignment is to get an input string, and using no string library functions to be able to handle the string. this code at the moment doesn't even print out the string i get in. when I remove the functions from main it magically starts to print. any help would be greatly appreciated
#include <stdio.h>
#include <string.h>
#define SIZE 32
int isQuit(char str[]);
void isPalindrome(char str[]);
int main (){
int cont = 0;
char str[SIZE];
fflush(stdin);
printf("please enter a word:\n");
scanf("%s\n", str);
printf("%s\n", str);
while(cont == 0)
{
scanf("%s\n", str);
printf("%s\n", str);
cont = isQuit(str);
isPalindrome(str);
}
return 0;
}
You most likely are suffering from line buffering in your terminal. Until you write a newline character, any characters written are not displayed.
Try adding a newline when displaying your input:
printf("%s\n", str);
The same goes for any other printf calls you do that you want to ensure are displayed.
By the way, your null-termination test is incorrect. The escape character is \, not /. Change your loop to:
while (str[h] != '\0')
Or simply:
while (str[h])
There are a few things wrong with your code here:
while(isQuit(str) == 0)
{
isPalindrome(str);
return 0 ;
}
Since you have the return keyword in your loop body (unconditionally), the loop will execute at most one time.
Also, neither isQuit nor isPalindrome take input from the user. This means that even if you were to fix the loop by removing the return statement, it still wouldn't be right; you'd have an infinite loop of isQuit and isPalindrome being passed the same str that the user got asked for on line 15.
What you have to do is change your while loop to continually poll the user for input and act upon it, in addition to the issues pointed out in #paddy's answer.
Related
as a homework assignment for my computing 1 college course, my professor has given me the task of having the user input a string of characters into the terminal, taking that string, adding it into an array, then printing the array and printing the array backwards. I think that I know of a way to print the array backwards, however, I cannot come up with a way to read from the terminal and add the characters from the terminal to an array. I have tried doing the following:
char ch;
for (int i = 0; i <= 80 || str[i] == '\n'; ++i) {
scanf_s("%c", &str[i]);
}
I am wondering if someone could explain to me why this section of code does not operate as expected, and if someone could give me some other ideas to try. Thank you.
You are using scanf_s with %c specifier incorrectly.
Please take notice of compiler warnings, there is a size argument missing.
Microsoft's scanf_s is not a direct replacement for scanf.
Unlike scanf ... scanf_s ... requires the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.
scanf_s("%c", &str[i], 1);
You might also want to filter out any newline which may have been left in the buffer, with
scanf_s(" %c", &str[i], 1);
notice the added space.
Why your code is showing this type of behaviour...
use scanf instead of scanf_s
the conditions you have provided in the for loop are wrong
#include <stdio.h>
int main()
{
char ch;
char str[1000];
int i;
for (i = 0; i <= 80 ; i++)
{
scanf("%c", &str[i]);
if(str[i]=='\n')
{
str[i]='\0';
break;
}
}
printf(str);
}
I could show you the same task in simple manner. I have tried to answer your question in your way. That's why it may seem complicated.
#include <stdio.h>
#define MAX 25
int main()
{
char buf[MAX];
fgets(buf, MAX, stdin);
printf("%s\n", buf);
return 0;
}
fgets- Reads until new line character encountered or maximum limit of character array.
I was using scanf for all my inputs in C. Now I saw other similar questions about scanf() and they suggested using fgets() instead of scanf(). I will do so in the future. However, at the moment this particular part of code with scanf() never seems to work. I know there is a solution.
My code is:
#define LENGTH 1000
#define WORD 100
int main(){
int i = 0;
char s[WORD][LENGTH];
do {
scanf("%s", s[i]);
i++;
}
while (s[i][strlen(s[i])] != EOF);
printf("%s\n", s);
return 0;
}
There should be something instead of EOF in the while loop which checks for the end of line. The final result should be an array of words in s[] and the program should print that array of words without spaces.
Unfortunately scanf() does not read the character you need to check for end of line, or at least not using "%s" as the specifier.
Instead, use the following
char line[100];
if (scanf("%99[^\n]", line) == 1) {
fprintf(stdout, "%s\n", line);
}
This way, it does not stop at white space characters, and it behaves similar to fgets(), except that it does not read the '\n' character and that might be a problem if you call it again.
I Am trying to make a program to make the user to enter his first name then middle then last name each followed by space like this example:
sample input: mark brown ashraf
sample output: m b a
and when i debug i got "access violation error"
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(void)
{
char name[100];
int i=0;
printf("Enter the name :");
gets(name);
while (name[i]!='\0')
{
if (name[i]==' ')
{
i++;
printf("%c",name[i+1]);
}
i++;
}
getch();
}
"now it dont give me the first initial but printed the rest of initials "
The access violation happens, because you use the wrong format specifier in your printf call.
printf("%s", name[i+1]);
should be
printf("%c", name[i+1]);
or maybe even more directly:
putchar(name[i+1]);
The violation occurs, because %s expects a pointer, which the printing function then dereferences. The char value you pass isn't a valid memory address.
Please switch on compiler warnings. They can usually tell you that your format string doesn't match the arguments.
Edit Besides the access violation, there are more problems in your program:
You increment i twice after a space, so that you actually print the second letter of each word. (Or even a space if your input is "Taylor C Huckleberry").
You don't catch the first word, unless your input begins with a space character.
You could end up printing the '\0' character when your input has trailing spaces.
You could print additional spaces if your input has subsequent spaces.
There are also some formal programming errors:
main is supposed to return an int, but your code never does.
You use the obsolete gets, which has been superseded with the more secure fgets. (Unformtunately, fgetskeeps a trailing newline, but it shouldn't matter for your code.)
In my opinion, a better approach is to keep track of the previously read character and to print the initial only if the previous char was a space and the current one is a letter. The header <ctype.h> provides the handy functions isspace and isalpha to check this. The previously read character starts off as a space character, so that you catch the first word:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char name[100];
char prev = ' '; /* pretend there's a space before the string */
int n = 0; /* number of initials printed */
int i = 0;
printf("Enter the name: ");
fgets(name, sizeof(name), stdin);
while (name[i]!='\0') {
if (isalpha(name[i]) && isspace(prev)) {
if (n++) putchar(' ');
putchar(name[i]);
}
prev = name[i];
i++;
}
putchar('\n');
return 0;
}
while (name[i]!='\0')
{
if (name[i]==' ')
{
i++;
printf("%s",name[i+1]);
}
i++;
}
SInce you are incrementing i twice inside the loop there is a possibility that you might have access array out of bound. This is a potential error.
gets() is no more a standard and you should use fgets() instead which will handle buffer overflow.
What's wrong in the below program (What's happening here)? It should break the for loop after the user inserts empty string (presses only ENTER), but in my case it ends in endless for loop. I tried what is in the comments with no success.
#include <stdio.h>
#include <string.h>
struct S {
char str [10];
};
int main(void)
{
int n;
struct S strings [10];
for (n = 0; n < 10; n++) {
# fflush(stdout);
scanf("%s", strings[n].str);
if (strlen(strings[n].str) == 0)
break;
# getchar();
}
printf("done");
return 0;
}
When I replace scanf with gets(strings[n].str); done is never printed. How would you fix it?
This sample solution works. Is there a difference in comparison to my code?
The enter key is not empty string, it is an ascii character or rather two characters a CR and LF (on Windows).
You shouldn't use strlen to find out if the input is empty. As others have said, when you press ENTER you get one or two characters sent to you.
You could instead check the first character in the string and see if it is '\n' or '\r'
scanf returns exactly what you've input... i.e. a crlf pair I'd imagine!
The problem with using scanf is that it expects something, not an empty string. You solve this by using e.g. fgets instead of scanf:
if (fgets(strings[n].str, sizeof(strings[n].str), stdin))
{
/* You got a string, it will contain the newline! */
}
#include <stdio.h>
#include <string.h>
int main()
{
int i;
int counter=0, counter2=0;
char *s;
char name[30];
char vowel[6] = "AEIOU";
char consonants[21] = "BCDFGHJKLMNPQRSTVWXYZ";
printf ("input the string: ");
scanf ("%s", name);
printf ("The string is %s\n", name);
for (i=0; name[i]!='\0'; i++) {
if (s = strchr(vowel, name[i])) {
counter++;
}
else if (s =strchr(consonants, name[i])) {
counter2++;
}
printf ("First counter is %d\n", counter);
printf ("The second counter is %d\n", counter2);
return 0;
}
}
And the question is, what is wrong with my code? why counter is not working?
Because I tried a lot of ways, and nothing works, maybe someone can explain for me.
I've added indentation to your code, and by doing this, it becomes quite obvious that your issue is that your return and print statements are inside the for loop. They should be outside the loop.
Apart from the } and { placement issue, consonants[21] should be consonants[22]. A safer way would be to use consonants[] - the compiler would count the number of characters for you.
The three last lines are:
return 0;
}
}
but should be:
}
return 0;
}
Lesson: indentation is important.
First, there are 21 consonants in the english alphabet, so your array should be 22 elements long (to accommodate the terminating '\0' char).
Second, you don't need to test for consonants at all, since if it's not a vowel it is a consonant. So you can clean this up by removing the consonants array completely, and simply using an else statement rather than redundantly checking your array for consonants.
Third, did you intend to print the value of each counter for each letter in name? That seems odd.
Also, you should only return once. Currently you're only going through the loop once, and then returning from main. That's not right... You should move both of the printf's and the return statement outside of your for loop. Thats all I got... Your code should run find if you make those fixes.
Don't use scanf to read strings of an arbitrary length:
#XXX never do that
char name[30];
scanf("%s", name);
If input is larger than the specified size then bad things can happen such as arbitrary code being executed.
You could use fgets instead:
char buf[BUFSIZ];
while (fgets(buf, sizeof(buf), stdin)) {
// buf contains a line or part of it;
// long lines are spread among multiple chunks
process_chunk(buf);
}
if (!feof(stdin))
; // error
It should be a comment; I've posted it as an answer to include the code example.
Nice use of strchr! One of my favorite functions in string.h. A few notes though:
You're only checking for uppercase characters. Take a look at toupper() to convert the test character to uppercase before comparing it to your vowel list.
If a character is a letter, and it's not a vowel, then it's a consonant. Instead of building up a separate array for consonants, take a look at the isalpha() function and think about how you could incorporate it into your program instead of a second call to strchr(). Now you don't have to worry about forgetting a character in the consonant list!