I have a piece of code here:
Tree *rangeprint(Tree *t) {
char first[20];
char last[20];
int f = 0;
int l = 0;
printf("First Entry?\n");
while(1) {
first[f] = getchar();
if(first[f] == '\n') {
first[f] = '\0';
break;
}
f++;
}
printf("Last Entry?\n");
while(1) {
last[l] = getchar();
if(last[l] == '\n') {
last[l] = '\0';
break;
}
l++;
}
printf("%s %s\n", first, last);
}
When I run this code, the output I get in the console is:
First Entry?
Last Entry?
Why is it skipping over the while loops and printing everything before executing them?
UPDATE - I changed the termination condition to 'x' instead of '\n' and sure enough it prints properly.
Adding a random getchar() before the loop starts fixes the problem, since the '\n' is read into there.
It is printing them, it's just that they are empty strings! (hint: f and l doesn't change - I assume the last loop using f is a typo!)
The getchar reads from the std in. If there is any newline character in previous input, It can cause the issue.
Just put,
fflush(stdin);
after
printf("First Entry?");
You are not advancing the pointer f while reading characters from the input. You are overwriting chatacter at location 0 all the times and in the end location 0 contains \0
try to put an \n at the end
printf("First Entry?\n");
printf("Last Entry?\n");
Related
I created a function that checks if a given string is a number or not.
The problem is that I take the input with fgets but ,when called, it doesn't stop to take input from user!
I tried to fix adding fflush(stdin) and fflush(stdout) to fix because I read some stuffs online but isn't working :S
getInput calls the fgets that stores the string taken from user input then isInt checks if it's an int or not.
The problem is that the program stucks on the first fgets.
int isInt (char* string)
{
int k=0;
while( string[k] != '\0')
{
if ( isdigit(string[k])==0) //it's k++ here, I copied bad
return 1;
}
return 0;
}
void getInput(char* string)
{
printf("Insert a number : \n");
while (1)
{
fflush(stdout); //Tried to fix
fflush(stdin); //same as above
fgets(string,sizeof(string),stdin); //stucks here
if(isInt(string)==0 )
{
printf("Ok it's a number!\n");
break;
}
else printf("Insert a valid number!\n");;
}
}
fgets() will put newline character read from the stream into the array, so remove that to avoid isInt returning 1 seeing the newline character.
sizeof(string) is the size of pointer, not the size of pointed buffer. You will have to receive the size of buffer separately. For more information, see C sizeof a passed array - Stack Overflow.
fflush(stdin); invokes undefined behavior, so you shouldn't use that.
You have to increment k in the loop in isInt, or it may stuck into an infinite loop. (thanks #Crowman)
#include <string> // for using strchr()
int isInt (char* string)
{
int k=0;
while( string[k] != '\0')
{
if ( isdigit(string[k])==0)
return 1;
k++; // increment k
}
return 0;
}
void getInput(char* string, size_t string_max) // add parameter to get buffer size
{
printf("Insert a number : \n");
while (1)
{
fflush(stdout);
fgets(string,string_max,stdin); // use passed buffer size instead of sizeof()
char* lf = strchr(string, '\n'); // find newline character
if (lf != NULL) *lf = '\0'; // and remove that if it exists
if(isInt(string)==0 )
{
printf("Ok it's a number!\n");
break;
}
else printf("Insert a valid number!\n");
}
}
I think that you should put the fgets inside the while condition:
while(fgets(string,sizeof(string),stdin))
I'm really new to programming and just wanted to ask a quick question.
So I made this program that reads off whatever the user inputs, then output the exact same thing until the user presses enter without any input.
int main(void) {
char s1[30];
while (s1[0] != NULL) {
gets(s1);
printf("%s\n", s1);
}
system("PAUSE");
return 0;
}
Then I realized that when I press enter to end the program, the program creates an extra blank line before the program terminates.
So I changed my code as it is below
int main(void) {
char s1[30];
while (1) {
gets(s1);
if (s1[0] == NULL)
break;
printf("%s\n", s1);
}
system("pause");
return 0;
}
And now the program terminates without creating an extra blank line. But I really can't seem to figure out the factors that made the difference between two codes.
Any help would be appreciated. Thanks!
As already told in the comment section don't use gets it is dangerous(why-is-the-gets-function-so-dangerous-that-it-should-not-be-used).
And replace gets with fgets as below.
while (fgets(s1,sizeof s1,stdin)) {
if (s1[0] == '\n') //fgets() reads the newline into the buffer
break;
printf("%s", s1); // Don't need to append \n to print as s1 will be having \n already.
}
To answer your question
gets(s1);
if (s1[0] == NULL) // Not valid comparison use \0 instead of NULL
When you press enter to terminate the program, gets will not read the newline(\n) character into the buffer hence your s1 will be untouched by gets and will have indeterminate values(seemingly it is having 0's in your case) so you are hitting if (s1[0] == NULL) and breaking out of the loop without printing newline.
I am in the process of writing a C program that parses a string and tokenizing it by breaking the string characters into words that are seperated by white space. My question is when i run my current program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[20];
printf("Please enter your word:\n");
scanf("%c", &input);
printf("%c", input[1]);
return 0;
}
If i was to enter the word "This", i would expect to get back "h" when i run the program but instead i get a downwards pointing arrow. However, when the input is set to print out input[0] i get back a "T".
Edit: I have modified my code so that it prints out the whole string now which i will show below
int main()
{
char input[20];
printf("Please enter your words:\n");
scanf("%s", input);
printf("%s", input);
return 0;
}
My goal is to be able to break that string into chars that i can search through to find whitespace and thus being able to isolate those words for example, if my input was "This is bad" i'd like the code to print out
This
is
bad
Edit:
I have modified my code to fit one of these answers but the problem i run into now is that it won't compile
int main()
{
char input[20];
printf("Please enter your words:\n");
size_t offset = 0;
do
{
scanf("%c", input + offset);
offset++;
}
while(offset < sizeof(input) && input[offset - 1] != '\n');
}
printf("%c", input[]);
return 0;
Problems:
1) scanf("%c", input); only set the first element of the array input.
2) printf("%c", input[1]); prints the second element of the array input, which has uninitialized data in it.
Solution:
Small state machine. No limit on string size like 20.
#include <ctype.h>
#include <stdio.h>
int main() {
int ch = fgetc(stdin);
while (ch != EOF) {
while (isspace(ch)) {
// If only 1 line of input allowed, then add
if (ch == '\n') return 0;;
ch = fgetc(stdin);
}
if (ch != EOF) {
do {
fputc(ch, stdout);
ch = fgetc(stdin);
} while (ch != EOF && !isspace(ch));
fputc('\n', stdout);
}
}
return 0;
}
scanf("%c", &input); does not do what you think it does.
First of all, %c scans only a single character: http://www.cplusplus.com/reference/cstdio/scanf/
Second, array's name is already a pointer to it's first element, so stating &input you make a pointer to a pointer, so instead of storing your character in array's first element you store it in pointer to the array which is a very bad thing.
If you really want to use scanf, I recommend a loop:
size_t offset = 0;
do
{
scanf("%c", input + offset);
offset++;
}
while(offset < sizeof(input) && input[offset - 1] != '\n');
Using scanf("%s", input") leaves you vulnerable to buffer overflow attacks if the word is longer than 20 characters http://en.wikipedia.org/wiki/Buffer_overflow
In my example I assumed, that you want to finish your word with a newline character.
EDIT: In scanf documentation is also a good example:
scanf("%19s", input);
It scans no more than 19 characters, which also prevent buffer overflow. But if you want to change input size, you have to change it two places.
You can use
char * strtok ( char * str, const char * delimiters );
to tokenize your string. If you have your input in input[] array and want to tokenize the string accoring to whitespace character, you can do the following :
char *ptr;
ptr = strtok(input, " ");
while(ptr != NULL) {
printf("%s\n", ptr);
ptr = strtok(NULL, " ");
}
Only the first call to strtok() requires the character array as input. Specifying NULL in the next calls means that it will operate on the same character array.
Your scanf only picks up the first character, input[1] contains random garbage. Use scanf("%19s", input) instead.
I have been asked to write a function that returns the first non-whitespace character in an inputted string.
It's working when I enter something like "hello" or anything that does not begin with a white space. But when I enter something like " hello", it returns a white space.
Here is my code:
int question6()
{
printf("Start typing stuff in \n");
char myChar = returnFirstNonWhite();
printf("First non-white space character is: %c",myChar);
}
int returnFirstNonWhite()
{
int ch,temp;
ch = getchar();
while (ch != 32)
{
temp = ch;
printf("Found first success %c\n", ch);
}
return temp;
}
ch = getchar();
while (ch == 32)
{
ch = getchar();
}
return ch;
One easy option would be to use scanf() instead of getchar(). scanf() will take a string (so there's no need to loop getting chars) and it will strip off any starting white space, so you just need to grab the first character it has.
int returnFirstNonWhite()
{
char str[50];
memset(str, '\0', 50);
scanf("%s", str);
return str[0];
}
so
>> hello
will return 104 (ascii 'h')
At first you are taking only one character input. And if it is not equal to 32 int value, the program should be in a infinite loop!!!! This is a nothing code.
Everything here appears to be okay, except in your while loop you don't continue to fetch the next character. In other words, it fetches the initial character, let's say a whitespace, and then continues in that while loop forever since the ch variable is never changed.
Try adding ch = getchar(); within your while loop so it continually fetches the next character to check. Also, I just realized you need to check that the character is equal to 32, not not equal so that if the character is a whitespace it continues to fetch the next character.
I'm trying to write code to count how many times a string repeats inside another one. (If there is some easier approach, please let me know.)
Here is the code that I have now:
int getStringLenght (char str[]) {
int lenghtOfTheString;
int i;
for (i = 0; i < 100; i++) {
if(str[i] == '\0') {
lenghtOfTheString = i;
break;
}
}
return lenghtOfTheString;
}
int main()
{
printf("Type a string: ");
char T[1024];
scanf("%s",&T);
char P[100];
printf("Type a substring: ");
scanf("%s",&P);
printf("%s",P);
int stringSize = getStringLenght (P);
int occurences = 0;
int i;
for (i = 0; i < 10; i++) {
int j;
if(T[i] == P[0]) {
for (j = 0;j<10;j++) {
char c1 = T[i+j];
char c2 = P[j];
if(c1 != c2) {
break;
}
if(j == stringSize-1) {
occurences++;
//printf("string iguais em i = %d",i);
}
}
}
}
printf("\nThe substring %s was found %d times", P, occurences);
return 0;
}
The app compiles. When I type "banana", for example, on the first scanf, and then "na" on the second, the app comes out with the right answer. But, if I type "banana and milk" on the first scanf, it automatically interprets the second scanf as "and", even when I don't type anything but "banana and milk ENTER"
What's happening?
scanf's "%s" conversion only reads characters until it encounters white-space (e.g., space, new-line, or tab). When you enter more than one word, it reads the first. The second call reads the second, and so on.
If you want to read an entire line, you usually want to use fgets instead (scanf can do the job as well, but it's a little trickier, and uses a feature of which many are unaware, so they often find it difficult to understand).
You don't understand how scanf works. http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ %s will only read one string, terminated by white space. If you want to keep reading strings, or read a line, you have to keep using scanf until one of your strings ends in a new line or EOF, or use another function, like fgets.
You have to remember that many functions are already implemented. This is why your getStringLength (you have typo in it's name) is needless. You can simply check the string's length using strlen function from string.h. What is more when you import this file you also have access to strstr function which finds the first occurrence of a given substring in a string. Try to use them instead of reinventing the wheel ;)
That is a standart problem with scanf. There are 3 ways to fix this:
1: Call fflush after each scanf:
scanf("%s", some_string); // you don't need to write &some_string because giving a array to a function automatically converts it to a pointer
fflush(stdin);
fflush() isn't available on every system.
2: Putting scanf in a loop:
do
scanf("%s", somestring);
while (getchar() != '\n');
3: Don't use scanf! Use fgets and sscanf!
char buffer[100]; // buffer for fgets()
fgets(buffer, 100, stdin); // read a line from stdin (standart input) into buffer
sscanf(buffer, "%s", some_string); // convert buffer in any format you want