Just need help with regards to this part, i'm meant to use scanf() to read a string from keyboard and return number of characters read, so i'm supposed to read a character string. The scan must then terminate at whitespace. A null character is stored at the end
of the string. However, the input string size from a user is arbitrary.

#include <stdio.h>                 /*Include the standard I/0 header file */
#include <string.h>                /*Include the standard I/0 header file string library */

int getInputByscanf(char input[]){
     char string[4];
     char phrase;
	 string = scanf("%c", &phrase);
		while (string != EOF){
			string = scanf("%c", &phrase)
   		}
     System("Pause");
	 return 0;    
}

is this right??

Recommended Answers

All 28 Replies

Not even close.

Your code does not insert any characters into the string array. What is the purpose of the "input" argument supplied to the function? where is the codes counting the number of characters read (or inserted into a string)? Where is code to make it terminate at whitespace? The length of the input string size may be arbitrary, but how does your code stop writing past the end of that length?

m pretty new to C n i dont know wat m doin wrong, it compiles fine buts gives me a warning "incompatible types in assignment".

is this right??

No.
scanf() returns an int, representing how many formats conversion was able to fulfill.
You use an array of chars string = scanf("%c", &phrase); Therefore string needs to be change to int, furthermore, every call to scanf will bring a new return. int result; result = scanf("%c", &phrase); will result in 1 if it was successful. result = scanf("%c%c%c", &char1, &char2, &char3); will result in 3 if it was successful.

ok i have changed it to this, but m gettin a warning "comparison between pointer and integer"

int getInputByscanf(char input[]){
     char string[4];
     int result;
	 result = scanf("%c", &string);
		while (string != EOF)
			string = scanf("%c", &string);
		
     System("Pause");
	 return 0;    
}

ok i have changed it to this, but m gettin a warning "comparison between pointer and integer"

int getInputByscanf(char input[]){
     char string[4];
     int result;
	 result = scanf("%c", &string);
		while (string != EOF)
			string = scanf("%c", &string);
		
     System("Pause");
	 return 0;    
}

result = scanf("%c", &string); string is an array of four. scanf() needs only one char. result = scanf("%c", &string[0]); will read one character into string[0] and return 1 into result.

[edit:] can you figure a loop so scanf() can use every subscript of string?

like a for loop???

A for loop could work. Any loop will do as long as you can control when scanf() will not read anything more from the input stream, and also will assign a char into every subscript of string except the last one which needs to be a '\0' to convert the whole thing into a string.

Be mindful that the user can enter one char or none (just the enter key), also it can input more that the string can hold, going over.

Are you meant to use %c?
Because %s will do the whole thing in one call.

ok i have changed it to this, but m gettin a warning "comparison between pointer and integer"

int getInputByscanf(char input[]){
     char string[4];
     int result;
	 result = scanf("%c", &string);
		while (string != EOF)
			string = scanf("%c", &string);
		
     System("Pause");
	 return 0;    
}

You still haven't pointed out why you are passing a character array as an argument. And your result variable seems redundant too. And as Salem pointed out it can be done using %s in scanf()like this: scanf("%s", string); . As for your whitespace condition, scanf ignores any input after the first whitespace.

For ex: scanf("%s", string); If user inputs "jared masc", only jared will be entered into the string variable. Here's a small piece of code to prove my point.

#include<stdio.h>
#include<stdlib.h>

int main()
{
char string[10];
printf("Enter string\n");
scanf("%s",string);
printf("%s",string);
system("pause");
return 0;
}

Hi,
If you just want to read a string with space termination, you could just use scanf...
If you want to print the read characters, just find the length of the string read and print it...
You said the user input is arbitrary, in that case you can do
1) read each character and reallocate memory until enter is pressed
2) allocate certain chunk of memory and read the string, if the memory already allocated runs out, reallocate again...
In the above cases you can keep a track of the characters read...
If you are not sure about allocation and reallocation of the memory, please check here and here and here ...
There are examples at the bottom of how to use it...

Happy Coding...

And yet, scanf can be clever function:

#include <stdio.h>

int main(){
    char dump, string[40];

    printf("Enter whole sentece (yeah, bring spaces too, I can handle it):\n");
    scanf ("%[^\n]", string);
    scanf("%c", &dump);
    printf ("You entered: %s", string);
    return 0;
}
scanf ("%[^\n]", string);
scanf("%c", &dump);

Yeah, the above code will take in whitespaces as well. Or you could use gets() or fgets() to be safe.Reason not to use gets(courtesy: Salem :))

Yeah, the above code will take in whitespaces as well. Or you could use gets() or fgets() to be safe.Reason not to use gets(courtesy: Salem :))

If you know what's wrong with gets() why do you say "Or you could use gets()". Why bring it up? Forget that exists. Period.

And yet, scanf can be clever function:

Nonetheless, it would not be very clever not to check the return of it.

commented: *nods* +23
commented: Just saying it's possible, although not safe. +1

I have the same question as Salem -- why are you reading one character at a time? And if you are passing input into the function, why are you not loading it for the return?

Also, FYI, see this and this about scanf() . Why instructors insist on teaching bad techniques I still have no idea. Maybe someone will ask sometime and post the response.

Nonetheless, it would not be very clever not to check the return of it.

Ahh, I knew someone will say something like that :)
Of course it can be dangerous, so are pointers (but we still use those).

Also, FYI, see this and this about scanf() . Why instructors insist on teaching bad techniques I still have no idea. Maybe someone will ask sometime and post the response.

For first this I have only one answer: scanf("%40s", string); For second this: yeah, you got me there, but I'm not talking how scanf is very cool, just that it CAN do a lot of things.

i changed this to 4 string[4] tat is, i then entered 5 characters, but its still printing out all of em, isnt it meant to print just 4 no matter wat???

#include <stdio.h>

int main(){
    char dump, string[40];

    printf("Enter whole sentece (yeah, bring spaces too, I can handle it):\n");
    scanf ("%[^\n]", string);
    scanf("%c", &dump);
    printf ("You entered: %s", string);
    return 0;
}

%s is a format substitute symbol. You are passing that to printf() and telling it to substitute for whatever string is contained in variable string, stopping where it finds a '\0'.
To access individual characters of that string the %c format specifier is used.
Placing a printf with %c inside a loop and incrementing the index subscript will imitate the same behavior that %s. scanf("%c", &dump); Do you understand what you are doing here?

i gt teh 1st part, but the main part is when the string is greater than 7, m meant to just take the first 4 letters(including spaces) and return, like example, if i enter morning, it must just take morn and return morn\0...

herez wat i have so far...

#include <stdio.h>
#include <string.h>

int main(){
	char dump, string[7];
	printf("Enter whole sentece (yeah, bring spaces too, I can handle it): ");
	scanf ("%[^\n]", string);
	scanf("%c", &dump);
	if(strlen(string) <= 7) 
		printf ("You entered: %s\\0\n", string);
	else
		printf("Try again");
	system("Pause");
	return 0;
}

i gt teh [...]
herez wat i have so far...

I have a hard time as it is understanding proper English; if you start cutting the words off and writing in chat mode I am afraid I won't be of much help. printf("Enter whole sentece (yeah, bring spaces too, I can handle it): No it can not handle it. string[7]; you can store only 6 characters plus the null terminator. scanf ("%[^\n]", string); you tell it to read until finds an new line. What happens when the user input more than six characters string? system("Pause"); it requires the inclusion of the header file stdlib.h

ok, but how do you take in just 4 letters or spaces despite the user entering more than 4??

ok, but how do you take in just 4 letters or spaces despite the user entering more than 4??

Honestly? You stop using scanf().
Use fgets() or create a function where you can control fgetc() or getchar().

Is scanf() part of the requirement? Can you read input using another function?

scanf is the only part i'm supposed to use unfortunately...

scanf is the only part i'm supposed to use unfortunately...

I am reluctant to give you a working code because I am afraid you are going to just copy and paste. But I also understand the frustration. scanf() is controlled by the while loop and stops when fails to read or find a new line.
the if inside the while loop controls how much it is keep from input. After while finishes input is clear. Modify it to your heart content.

#include <stdio.h>

int main(void) {
    char str[7] = { '\0' };
    int i = 0;
    char ch;

        /* everything from imput will be read */ 
        while ((scanf("%c", &ch) == 1) && ch != '\n') {
            if (i < 6) { /* keep only six characters from input */
                str[i] = ch;
                ++i;
            }
        }

    printf("%s", str);
    return 0;
}
commented: very helpful +1

The easiest command I've found to capture strings is "gets(string)" to set the string to your variable then just "puts(string)" to display it

The easiest command I've found to capture strings is "gets(string)" to set the string to your variable then just "puts(string)" to display it

Easiest, sure. But with that ease comes a significant and unavoidable risk of buffer overflow because gets doesn't know when to stop copying characters to the array, and there's no way to stop it.

fgets is only slightly more complicated, and much safer. You can still pair it with puts, though some introspection about the trailing newline (that gets throws away, but fgets stores) is needed:

if (fgets(string, sizeof string, stdin) != NULL) {
    char *p = strchr(string, '\n');

    if (*p == NULL) {
        // No newline, partial line was read
        panic("Unexpectedly long line);
    }

    *p = '\0'; // Trim the newline so puts works consistently

    puts(string);
}

with ease comes a significant and unavoidable risk of buffer overflow

I've never experienced that problem, but I have only been even using strings in my codes for 1 day :P the only problem I've had from gets is that sometimes (I've only had one case of this) it get's skipped and you have to put the same gets function twice to prevent that

I've never experienced that problem

Just because you haven't experienced a problem doesn't mean it doesn't exist. Most of the time people who only use gets in toy programs and are the only ones typing input will pull out the "it's never happened to me" fallacy. Here's a socratic question:

char buf[10];
gets(buf);

What happens if in the above code, you type more than 9 characters? Further, what if stdin is redirected to a file that you don't control?

the only problem I've had from gets is that sometimes (I've only had one case of this) it get's skipped and you have to put the same gets function twice to prevent that

That's not a problem with gets. It's a problem with not understanding how stream I/O works. You're mixing formatted (ie. scanf) and unformatted (ie. gets) input such that the formatted input leaves a newline in the stream and the unformatted input successfully terminates on it immediately.

The usual recommendation to get around that problem is always use unformatted input from the source stream, then parse the result using something like sscanf.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.