So... the main question is how I can use the string that the user entered in another function? I know it would be a lot easier to do it all in the main function but we are forced to use as many separate ones as possible. Thanks in advance.
Following on from the comment, you most likely want to declare the str in a scope available to both functions:
int enterWord (char *str) {
...
scanf("%24s", str);
...
return str[0];
}
int menuScan (char *str) {
...
}
int main (void) {
char str[25] = {0};
int someint;
...
someint = menuScan (enterWord (str));
return 0;
}
or
int main (void) {
char str[25] = {0};
int someint, someotherint;
...
someint = enterWord (str);
...
someotherint = menuScan (str);
return 0;
}
You may want to employ a bit of additional error checking on the user input as well, e.g.:
int enterWord (char *str) {
printf ("Please enter a single word that is no more than 25 characters: ");
if (scanf ("%24s", str))
printf ("\nThanks! You entered: %s", str);
else
return -1;
return str[0];
}
...
int main (void) {
char str[25] = {0};
int someint, someotherint;
...
if ((someint = enterWord (str)) = -1) {
fprintf (stderr, "enterWord() error: input failure.\n");
return 1;
}
...
someotherint = menuScan (str);
return 0;
}
Remaining Issue With '\n' Left In Input Buffer
Your remaining problems come from the fact that after you call scanf, you are leaving the '\n' (cause by pressing [Enter]) in the input buffer stdin. The next time your program calls scanf it takes the '\n' left in the input buffer as the user input. (if you check, you will find it is using the value 0xa (or 10) which is the value for newline)
You have two options. You can use a loop to empty stdin:
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
You can also use the assignment suppression operator of scanf to read and discard the newline, e.g.:
scanf ("%24[^\n]%*c", str)
Where %24[^\n] read upto 24 chars (not including the '\n' into str) and %*c which reads and discards a single character (the newline). That way your input buffer is empty before the next user input.
Here is a short working example:
#include <stdio.h>
int enterWord (char *str);
void menuOptions ();
int menuScan (char *str);
int main (void) {
char str[25] = {0};
if (enterWord (str) == -1) {
fprintf (stderr, "enterWord() error: input failure.\n");
return 1;
}
do {
menuOptions();
} while (!menuScan (str));
return 0;
}
int enterWord (char *str)
{
printf ("Please enter a single word that is no more than 25 characters: ");
if (scanf ("%24[^\n]%*c", str))
printf ("\nThanks! You entered: %s", str);
else
return -1;
return str[0];
}
void menuOptions ()
{
printf("\n\n========= MENU =========\n\n");
printf("Key Function\n");
printf("=== ========\n");
printf(" C Count the letters\n");
printf(" V Count the vowels\n");
printf(" R Reverse the word\n");
printf(" P Check if the word is a palindrome\n");
printf(" W Enter a new word\n");
printf(" Z Exit\n\n");
}
int menuScan (char *str)
{
/* always initialize variables */
char *p = str;
char menuChoice = 0;
int c = 0;
int charcnt = 0;
printf ("Please enter a character from the options above: ");
if (!scanf ("%c%*c", &menuChoice)) {
fprintf (stderr, "menuScan() error: input failure.\n");
return -1;
}
printf ("\nYou entered: %c\n", menuChoice);
c = menuChoice; /* I don't like to type */
/* validate input */
if (c < 'A' || ('Z' < c && c < 'a') || 'z' < c) {
fprintf (stderr, "menuChoice() error: input is not [a-z] or [A-Z]\n");
return -1;
}
/* convert to lowercase */
if ('A' <= c && c <= 'Z') c += 32;
switch (c) {
case 'c':
for (; *p; p++) charcnt++;
printf ("\n\nThere are '%d' letters in '%s'\n", charcnt, str);
break;
case 'z':
return -1;
default : printf ("(%c) invalid choice -> try again.\n", c);
}
return 0;
}
Compile
gcc -Wall -Wextra -finline-functions -O3 -o bin/menuscan menuscan.c
Example/Use
$ ./bin/menuscan
Please enter a single word that is no more than 25 characters: 0123456789
Thanks! You entered: 0123456789
========= MENU =========
Key Function
=== ========
C Count the letters
V Count the vowels
R Reverse the word
P Check if the word is a palindrome
W Enter a new word
Z Exit
Please enter a character from the options above: c
You entered: c
There are '10' letters in '0123456789'
========= MENU =========
Key Function
=== ========
C Count the letters
V Count the vowels
R Reverse the word
P Check if the word is a palindrome
W Enter a new word
Z Exit
Please enter a character from the options above: z
You entered: z
There are a lot of problems with your code, but I will address only the actual question you posed.
When you have a function which creates a result value to be used somewhere else, you need to return that value when the function ends. The 'return' keyword will do this, but you must bear in mind that the thing being returned must continue to exist after the function has ended (as noted by #David C. Rankin in the comments).
Locally declared variables will cease to exist when the function ends, so the solution is to declare them in a wider scope.
// declare the string in a wider scope
// provide one extra character space for the string terminator \0 character
char inputStr[25 + 1];
// pass the string to the function which will fill it with the entered string
// NOTE: to avoid risk of someone entering too many letters in the string, we
// also pass in the length of the string buffer
enterWord(inputStr, 25);
The changes to the enterWord function would be:
void enterWord(char* str, int length){
printf("Please enter a single word that is no more than %d characters: ", length);
// this should verify the length of the entered text to make sure it isn't too long... but that's not your question
scanf("%s", str);
printf("\nThanks! You entered: %s", str);
}
In the scope where you declared inputStr, the string will now contain the data entered by the user.
In this case we are returning the string from the function by a different mechanism than the 'return' keyword. Here we are passing a pointer to the first letter of the buffer space, so that the function will fill the original inputStr buffer from inside the function.
If you must use a more 'functional' coding paradigm, you might want to consider allocating space for the buffer on the heap using 'malloc', you would then need to remember to use 'free' at a later point in the code to release that allocated memory and avoid a memory leak, which is why that would not be my preferred solution in this case.
Related
I have written this code but I have a little problem with it.
This code should get a string and check whether this string contains all the alphabet letters...
If it doesnt the output is "Not a pangramma!".
If it does "PanGramma!".
The probem is that I want it to count also the nuumber of the spaces between the words. But when the input is string with at least one space the output will always be "Not a PanGramma!", even if it contains all the alphabet letters.
Can someone please help me?
#include <stdio.h>
char UpCase (char c);
int isPangram (char *str);
int main()
{
char str[100];
printf("Please enter yout string: \n");
scanf("%s", str);
if (isPangram (str) == 1)
{
printf("PanGramma!\n");
}
else
{
printf("Not a PanGramma!\n");
}
return 0;
}
char UpCase (char c)
{
if (c>='a' && c<='z')
{
return c-'a'+'A';
}
return c;
}
int isPangram (char *str)
{
int i=0;
int hist[27]={0};
while (str[i] !=0)
{
str[i]=UpCase(str[i]);
if (str[i] == ' ')
{
hist[26]++;
}
else
{
hist[str[i] - 'A']++;
}
i++;
}
for (i=0; i<26; i++)
{
if(hist[i] == 0)
{
return 0;
}
}
return 1;
}
Your problems comes from the usage of scanf function: it does stops at each white space it catch.
From man scanf:
%s
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
To make your program to work, you can use fgets function:
int main()
{
char str[100];
printf("Please enter yout string: \n");
fgets(str, sizeof str, stdin);
if (isPangram (str) == 1)
{
printf("PanGramma!\n");
}
else
{
printf("Not a PanGramma!\n");
}
return 0;
}
If you want to know more on scanf function, you can read A beginners' guide away from scanf(). It will also tell you why scanf could cause a buffer overflow in your code.
Thank you guys!
I have used this
scanf ("%[^\n]%*c", str);
thanks once again for your help!
I was working on this sample exercise, and everything works as I would like it to, but there is one behavior I don't understand.
When providing input: if I make consecutive invalid entries everything seems to work great. But if I enter a number different from 1,2,3 in the case of the first question, or 1,2 in the case of the second question, the program just sits there until a new input is given. If another invalid entry is made, it goes back to the error "invalid entry" message, and if an appropriate number is entered, everything moves along fine.
I do not understand why it stops to wait for a second input...anyone?
Thanks guys.
#include <stdio.h>
static int getInt(const char *prompt)
{
int value;
printf("%s",prompt);
while (scanf("%d", &value) !=1)
{
printf("Your entry is invalid.\nGive it another try: %s", prompt);
getchar();
scanf("%d", &value);
}
return value;
}
int main() {
int wood_type, table_size, table_price;
printf("Please enter " );
wood_type = getInt("1 for Pine, 2 for Oak, and 3 for Mahogany: ");
printf("Please enter ");
table_size = getInt("1 for large, 2 for small: ");
printf("\n");
switch (wood_type) {
case 1:
table_price = (table_size == 1)? 135:100;
printf("The cost of for your new table is: $%i", table_price);
break;
case 2:
table_price = (table_size == 1)? 260:225;
printf("The cost of for your new table is: $%i", table_price);
break;
case 3:
table_price = (table_size == 1)? 345:310;
printf("The cost of for your new table is: $%i", table_price);
break;
default:
table_price = 0;
printf("The cost of for your new table is: $%i", table_price);
break;
}
}
You most likely need to flush your input buffer (especially with multiple scanf calls in a function). After scanf, a newline '\n' remains in the input buffer. fflush does NOT do this, so you need to do it manually. A simple do...while loop works. Give it a try:
edit:
static int getInt(const char *prompt)
{
int value;
int c;
while (printf (prompt) && scanf("%d", &value) != 1)
{
do { c = getchar(); } while ( c != '\n' && c != EOF ); // flush input
printf ("Invalid Entry, Try Again...");
}
return value;
}
The blank line you get if you enter nothing is the normal behavior of scanf. It is waiting for input (some input). If you want your routine to immediately prompt again in the case the [Enter] key is pressed, then you need to use another routine to read stdin like (getline or fgets). getline is preferred as it returns the number of characters read (which you can test). You can then use atoi (in <stdlib.h>) to convert the string value to an integer. This will give you the flexibility you need.
example:
int newgetInt (char *prompt)
{
char *line = NULL; /* pointer to use with getline () */
ssize_t read = 0; /* number of characters read */
size_t n = 0; /* numer of chars to read, 0 no limit */
static int num = 0; /* number result */
while (printf ("\n %s ", prompt) && (read = getline (&line, &n, stdin)) != -1)
{
if ((num = atoi (line)))
break;
else
printf ("Invalid Input, Try Again...\n");
}
return num;
}
If some invalid input is entered, it stays in the input buffer.
The invalid input must be extracted before the scanf function is completed.
A better method is to get the whole line of input then work on that line.
First, put that input line into a temporary array using fgets(),
then use sscanf() (safer than scanf because it guards against overflow).
#include <stdio.h>
int main(int argc, const char * argv[]) {
char tempbuff[50];
int result, d , value;
do
{
printf("Give me a number: ");
fgets( tempbuff, sizeof(tempbuff), stdin ); //gets string, puts it into tempbuff via stdin
result = sscanf(tempbuff, "%d", &value); //result of taking buffer scanning it into value
if (result < 1){ //scanf can return 0, # of matched conversions,
//(1 in this case), or EOF.
printf("You didn't type a number!\n");
}
}while (result < 1);
//some code
return 0;
}
Knowledge from: http://www.giannistsakiris.com/2008/02/07/scanf-and-why-you-should-avoid-using-it/
Practice.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARR 32
int main(void){
int MEM=64;
char arr[ARR],*p=(char *)calloc(MEM,(sizeof(char))),*q=NULL;
int i=0,j=1;
printf("\nEnter String : ");
while(j){
scanf(" %[^\n]s " ,arr);
if(j==1)
strcpy(p,arr);
else
strcat(p,arr);
if((j*ARR)==MEM){
MEM=MEM+(j*ARR);
q=realloc(p, MEM);
if(!(q)){
printf("\nNOT ENOUGH MEMORY\n");
goto END;
}
p=q;
}
for(i=0;i<(strlen(arr));++i){
if(arr[i]=='\n')
break;
}
if(arr[i]=='\n')
break;
++j;
}
printf("\n %s\n",p);
END: free(p);p=NULL;q=NULL;
return 0;
}
I am trying to get multiple string inputs.
I am using scanf(" %[^\n]s",arr); to take the input instead of fgets(arr,ARR,stdin);, because with fgets the program execution stops as soon as I hit ENTER key. But with scanf(" %[^\n]s",arr); the program is unable to get out of the while() loop even after entering \n.
I would like to know the mistake or mistakes I have made while writing the code.
The canonical way of reading multiple lines of input in C is to use fgets in a loop, like
while (fgets(arr, sizeof(arr), stdin) != NULL)
{
if (arr_contains_special_input_to_exit_loop(arr))
break;
// Optionally check for and remove trailing newline from input
// Append `arr` to your data
}
The condition to exit the loop might be some special input or an empty line or something else completely.
One mistake is:
for(i=0;i<(strlen(arr));++i){
if(arr[i]=='\n')
break;
}
Looking earlier in you code you have:
scanf(" %[^\n]s " ,arr);
The [^\n] prevents any newlines \n from being contained in arr. So your loop that looks for (arr[i]=='\n') will never find any. Your next bit of code continues looking for non-existent newlines:
if(arr[i]=='\n')
break;
This last break also breaks out of your outer loop preventing you from asking for further input on finding a newline (which it shouldn't). Fix these issues and it should get much further allowing you to enter multiple items.
Edit:
With a bit of effort looking at what you were doing, I now have it taking multiple input and reallocating as necessary. The strings are all concatenated and printed at the end. It could still stand a bit of work, but this should give you a few hints:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARR 32
int main (void) {
int MEM = 64;
char arr[ARR], *p = (char *) calloc (MEM, (sizeof (char))), *q = NULL;
int i = 0, j = 1;
while (j) {
printf ("\nEnter String : ");
scanf (" %[^\n]s ", arr);
printf (" you entered (arr): %s\n", arr);
if (strcmp (arr, "q") == 0) {
printf ("\n 'q' entered, exiting.\n\n"); // provide for exit if `q` entered
break;
}
if (j == 1)
strcpy (p, arr);
else
strcat (p, arr);
if ((j * ARR) == MEM) {
MEM = MEM + (j * ARR);
q = realloc (p, MEM);
if (!q) {
printf ("\nNOT ENOUGH MEMORY\n");
goto END;
}
else
printf ("\nMemory Reallocation - succeeded.\n");
p = q;
}
++j;
}
printf (" %s\n", p);
END:
if (p) free (p); /* always test pointer before calling free */
p = NULL;
q = NULL;
return 0;
}
output:
./bin/me
Enter String : fishinsea
you entered (arr): fishinsea
Enter String : alligators
you entered (arr): alligators
Memory Reallocation - succeeded.
Enter String : really_big_mosters
you entered (arr): really_big_mosters
Enter String : SuperSnake_Prudhome
you entered (arr): SuperSnake_Prudhome
Memory Reallocation - succeeded.
Enter String : 8_puppies
you entered (arr): 8_puppies
Enter String : q
you entered (arr): q
'q' entered, exiting.
fishinseaalligatorsreally_big_mostersSuperSnake_Prudhome8_puppies
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.
#include<stdio.h>
#include<stdlib.h>
#define n ((sizeof(char)) * 100 )
int stringlength(char * str)
{
int count=0;
while(*str)
{
if(*str == '\n')
{
*str=0;
}
else
count++, str++;
}
return count;
}
int palin1(char *str, int k)
{
char * pend = str + k - 1;
if(*pend != *str)
return 0;
else
palin1(str+1, k-1);
return 1;
}
int palin(char *str)
{
int length = stringlength(str), f=0;
char *pend = str + length - 1;
while(str <= pend)
{
if(*str == *pend) f=1;
else
return (f = 0);
str++, pend--;
}
return 1;
}
main()
{
char * ps = (char *)malloc(n);
int flag;
if(ps == NULL) printf("Malloc Fail\n");
else
{
printf("Malloc Succeeded, you have memory of %d bytes\n", n);
printf("This program checks if String is Palindrome or not\n\
\nEnter your String: ");
fgets(ps, 100, stdin);
printf("You entered: %s of length %d", ps, stringlength(ps));
int i = 0;
printf("\n\nEnter:\n1.Using iteration\n2.Using Recursion ");
scanf("%d", &i);
switch(i)
{
case 1:
flag=palin(ps);
break;
case 2:
flag=palin1(ps,stringlength(ps));
break;
default:
printf("Invalid input");
}
if(flag) printf("\nYou entered a Palindrome");
else printf("\nNot a Palindrome");
}
free (ps);
return 0;
}
Why does the above program http://www.ideone.com/qpGxi does not give any output on putting the input:
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
I know fgets(ps,100,stdin) will take only 100 characters and not more than that, but why does the program halt execution?
You should check for fgets failure, as recommended by the fgets spec.
if ( fgets(ps,100,stdin) == NULL ) {
printf("Input failed.");
//check for 'feof' or 'ferror' here
return -1;
}
printf("You entered: %s of length %d",ps,stringlength(ps));
I don't see why fgets would be failing, but you would get an uninitialized character buffer back, which would crash printf.
EDIT: You should really pay attention to your compiler warnings, too.
prog.c:49: warning: return type defaults to ‘int’
prog.c: In function ‘main’:
prog.c:59: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
prog.c:63: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
prog.c: In function ‘palin’:
prog.c:46: warning: control reaches end of non-void function
prog.c: In function ‘main’:
prog.c:52: warning: ‘flag’ may be used uninitialized in this function
You can see that even your compiler recommends checking fgets for null. Also, flag should be set to 0 in the default case, otherwise you will get undefined behavior if the user enters something other than 1 or 2.
EDIT 2: Oh for Christ's sake! your program works fine! You forgot to check "run program" in Ideone!!!
http://www.ideone.com/7ecZd
You cannot break a string literal just like that
printf("%s\n", "string literal **WRONGLY**\n
broken right after the line break.");
What you can do is use the preprocessor feature of joining successive string literals to make just one
printf("%s\n", "string literal **CORRECTLY**\n"
"broken because the preprocessor joins these 2 parts.");
It's terminating because there are characters left in the input stream if the input is too large. For example, if you wish to take only 5 characters using fgets but have given the input as -
StackOverflow
Overflow are left in the input stream. They need to be removed from the stream for further input operations to succeed. So, remove those extra characters from the stream using -
fgets(ps,100,stdin);
while (getchar() != '\n');
Since the input stream is struck with offending characters, the scanf statement that actually takes the user input is not working and jumping to subsequent operations.
Also initialize the flag variable to 0 other wise it has garbage values.