Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
1.actually I want to first give a number N (no. of strings I want to enter) as an input then in next line a string using gets().But when I press enter then the no. of strings I could enter is N-1.I tried using printf("\n") but it didn't work.Please anyone could help me in this.eg:
//code
int N,i,arr[N];
char str[50];
scanf("%d",&N) //no. of strings required
for(i=0;i<N;i++)
{
gets(str);
arr[i]=strlen(a);
}
for(i=0;i<N;i++)
{
printf("%d\n",arr[i]);
}
i want to enter my input to be like this:
2 //no. of strings
ABCFD //string 1
ASWD //string 2
//But actually what i am getting using printf("\n")
and output:
5
4
but what i am getting:
2
//blank space
ASWD //string 2
and output
0
4
After entering a value for N there remains a newline in the input buffer, which is accepted by the following gets as a blank input. In any case gets is a deprecated function: please use fgets such as like this. I've printed each entry to show there is a newline at the end of each, and removed that newline.
#include <stdio.h>
#include <string.h>
int main(void) {
int N, i;
char str[50];
printf("Enter number of cases\n");
scanf("%d%*c", &N); // read newline too, but discard
for(i=0; i<N; i++)
{
printf("\nEnter string\n");
if (fgets(str, sizeof str, stdin) == NULL)
return 1;
printf("Shows newline >>%s<<\n", str); // show that newline is retained
str [ strcspn(str, "\r\n") ] = 0; // remove trailing newline
printf("After removal >>%s<<\n", str); // show that newline was removed
}
return 0;
}
Program output
Enter number of cases
2
Enter string
one
Shows newline >>one
<<
After removal >>one<<
Enter string
two
Shows newline >>two
<<
After removal >>two<<
Try it --
int lineNumbers;
scanf("%d", &lineNumbers);
char **linesOfString = (char**) malloc(lineNumbers * sizeof(char *));
int i;
for(i = 0; i < lineNumbers; i++) {
fflush(stdin);
linesOfString[i] = (char *) malloc(255 * sizeof(char));
scanf("%s", linesOfString[i]);
}
for(i = 0; i < lineNumbers; i++) {
printf("%s", linesOfString[i]);
}
free(linesOfString);
return 0;
It sounds like you are not getting the number of strings expected, is this correct?
If this is the case, look at your looping code.
The most likely newbie mistake is with indexing. Arrays in C are 0 indexed.
This means that if you have int test[3], the indexes of test will be 0, 1, and 2. This means that the highest index WILL be N-1.
So, make sure that the first string you are accepting is being placed into index 0, and not index 1.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
If a user inputted:
1 2 3 4 5 0
How would I transform it into an array with 5 elements (The 0 integer indicates termination)? Also, in the code I need to ensure it works for up to 500 integers.
I have no clue how to proceed. I am thinking of using gets and saving it into an allocated space:
char *ptr;
ptr = malloc(sizeof(char) * 1000);
fgets(ptr, sizeof(char)*1000, stdin);
The problem here is I am not sure how to allocate the space as each digit will be saved as a character and each integer may have different number of digits.
Afterwards, I am not sure how to split it into array.
Could someone advise me on how to continue or if my method is not good?
I know I have not done a lot but I am really confused. I have looked up on gets(), fgets(), scanf(), fscanf(), and am still not sure.
Thanks!
You can parse the line input by the user with sscanf() or strtol():
#include <stdio.h>
int main() {
char buf[256];
int array[5];
if (fgets(buf, sizeof buf, stdin)) {
if (sscanf(buf, "%d%d%d%d%d", &array[0], &array[1], &array[2], &array[3], &array[4]) == 5) {
// array has the 5 numbers input by the user.
printf("%d %d %d %d %d\n", array[0], array[1], array[2], array[3], array[4]);
}
}
return 0;
}
For generic code that works up to 500 numbers, you can just use scanf() in a loop:
#include <stdio.h>
int main() {
int array[500];
int i, n;
for (n = 0; n < 500; n++) {
if (scanf("%d", &array[n]) != 1) {
printf("invalid input\n");
return 1;
}
if (array[n] == 0) {
// 0 indicates termination
break;
}
}
// the array has n valid non-zero numbers
printf("The numbers are:\n");
for (i = 0; i < n; i++) {
printf(" %d\n", array[i]);
}
return 0;
}
You could use a character array with a combination of fgets() and strtok().
First declare a character array str and set a flag variable.
char str[100];
int flag=1;
flag may be made 0 when input 0 is found.
As long as flag is 1 use fgets() to read a line of input (provided fgets() is successful) as in
while(flag==1 && fgets(str, sizeof(str), stdin)!=NULL)
{
.....
.....
}
Now inside this loop, use strtok() to tokenize the string in str using space and \n as delimiters. \n is made a delimiter because fgets() reads in the trailing \n to str as well.
for(ptr=strtok(str, " \n"); ptr!=NULL; ptr=strtok(NULL, " \n"))
{
n=atoi(ptr);
if(n==0)
{
flag=0;
break;
}
printf("\n%d", n);
}
Convert the tokens produced by strtok() to integers. I used atoi() for brevity but it is not the best way. strtol() might be a good idea. See here.
I would suggest something like this
#include "rlutil.h" //a good library similar to conio.h or it's Linux equivalent but cross-platform. You have to include it manually and download it at github.
int i = 0;
int num = 1;
char input;
int array[255];
for (i = 0; num = 0; i++)
{
input = getchar();
num = input - '0';
array[i] = num;
printf("%i ", num);
}
Just pay attention to the size of the array.
Furthermore you could parse the string you got with fgets with strtok. If you want I can edit this post later and include this variant.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So I'm trying to make a code that checks if a word is a palindrome. So, I reversed the user inputted word and checks if the words are equal. However, it always returns "Not equal". Can someone be kind enough to explain why this doesn't work?
#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 200
int main() {
char s[STRING_LENGTH] = {0};
fgets(s, STRING_LENGTH, stdin);
int Ordlengde = strlen(s) - 1;
printf("The word contains %i letters", Ordlengde);
int i;
char palindrom[STRING_LENGTH];
int x = 0;
for (i = Ordlengde; i >= 0; --i)
{
palindrom[x++] = s[i];
}
int Ordlengde1 = strlen(palindrom) - 1;
printf("The word contains %i letters", Ordlengde);
printf("\nThe word reversed is %s", palindrom);
printf("%s",s);
if (strcmp(s , palindrom) == 0)
printf("are equal\n");
else
printf("are not equal \n");
return 0;
}
The actual problem was failing to remove the trailing newline. It sometimes helps to quote your output for easy recognition of non-printing character problems like tabs, newlines, etc.. Doing so immediately reveals the problem. (note: where the quotes end up with your original logic)
$ ./bin/palindrome
foo
The word contains 3 lettersThe word contains 3 letters
The word reversed is '
oof' <-> 'foo
' (original) are not equal
(you are comparing \noof with foo\n which was failing)
Correcting the newline removal and tidying things up a bit, your logic for the reversal and check works fine, e.g.
#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 200
int main() {
int x = 0, Ordlengde;
char s[STRING_LENGTH] = "",
palindrom[STRING_LENGTH] = "";
printf ("enter a word: ");
if (!fgets (s, STRING_LENGTH, stdin)) { /* VALIDATE INPUT */
fprintf (stderr, "error: invalid input - EOF.\n");
return 1;
}
Ordlengde = strlen(s) - 1;
if (s[Ordlengde] == '\n') /* check/remove '\n' */
s[Ordlengde] = 0;
while (Ordlengde--) /* reverse s */
palindrom[x++] = s[Ordlengde];
printf ("\noriginal: '%s'\nreversed: '%s' - ", s, palindrom);
if (strcmp(s , palindrom) == 0) /* compare */
printf("is a palindrom\n");
else
printf("is not a palindrom\n");
return 0;
}
Example Use/Output
$ ./bin/palindrome
enter a word: foo
original: 'foo'
reversed: 'oof' - is not a palindrom
$ ./bin/palindrome
enter a word: foof
original: 'foof'
reversed: 'foof' - is a palindrom
A couple of final notes. First, if you are expecting user input, then prompt for it. Otherwise, you leave the user looking at a blinking cursor on the console -- wondering if the program is hung. Sure, you know you need to enter a word, but thing about someone else running your code for the first time. Nothing special is needed, just a simply prompt:
printf ("enter a word: ");
Next, I would recommend the "traditional" check with the full length of the string minus 1. Why? What if the string was 201 characters long? There would be no new line at the end... That's why the traditional check below will preserve the original length until you confirm there is a newline to trim:
Ordlengde = strlen(s);
if (Ordlengde && s[Ordlengde - 1] == '\n') /* remove '\n' */
s[--Ordlengde] = 0;
Keep at it and good luck with your coding.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have the following problem reading two strings through scanf: I insert the first string and everything it's OK, but after I insert the second one the first one changes.
#include<stdio.h>
#define N 6
#define K 2
int main(){
char a[N];
char b[K];
int i = 0,j=0;
printf("first word\n\n\n");
scanf("%s", a);
for(i = 0; i <= N; i++){
printf("%c", a[i]);
}
printf("second word \n\n\n");
scanf("%s", b);
for(i = 0; i <= N; i++){
printf("%c", a[i]);
}
}
The first time it prints it correctly. The second time it prints a similar string (maybe the first scanf is still getting the input when I'm inserting the second one)
To begin, you are printing the array a twice; it seems that you mean to print b with the second loop. But there is a problem in your loops. They are going out of array bounds. Since arrays are zero-indexed in C, you need:
for (i = 0; i < N; i++) {}
for a, and:
for (i = 0;i < K; i++) {}
for b.
But even this is not quite right, since the input strings may not entirely fill the arrays. You really need to terminate the loop when the null-terminator is reached, or when the end of the array has been reached:
for (i = 0; a[i] != '\0' && i < N; i++) {}
and:
for (i = 0; b[i] != '\0' && i < K; i++) {}
Of course, it would be simpler to just use puts() to print the strings.
It seems that the inputs (abcabc and abc) were too large for the arrays, causing buffer overflow. This can be avoided by specifying maximum widths when using the %s conversion specifier with scanf().
Here is a modified version of the posted code. I increased the sizes of N and K by one, since it appears that space for null-terminators was not considered in the original code:
#include <stdio.h>
#define N 7
#define K 3
int main(void)
{
char a[N];
char b[K];
int i = 0;
printf("first word\n\n\n");
scanf("%6s", a);
for (i = 0; a[i] != '\0' && i < N; i++) {
printf("%c", a[i]);
}
putchar('\n');
printf("second word \n\n\n");
scanf("%2s", b);
for (i = 0; b[i] != '\0' && i < K; i++) {
printf("%c", b[i]);
}
putchar('\n');
return 0;
}
You are printing a twice, change the second printf("%c", a[i]); to printf("%c", b[i]); .
The problem you are experiencing is because you invoke undefined behavior by failing to insure the strings are nul-terminated and by using incorrect limits regarding b. For instance, you
#define N 6
#define K 2
...
char a[N], b[K];
a can hold a total of 5-chars + the nul-terminator, for a total of 6-chars. b on the other hand, can only hold 1-char + the nul-terminator for a total of 2-chars.
When you then subsequently loop of both a and b with for(i = 0; i <= N; i++), not only have you guaranteed to access an element outside the bounds of the array, e.g. a[6] (valid indexes are 0-5), you have also invoked undefined behavior for any a with less that 6 total characters by attempting to read from an uninitialized value (those uninitialized array elements after the last valid char in word of say, 3-chars) When you invoke Undefined Behavior, the execution of your code is unreliable from that moment forward.
In your case you can eliminate undefined behavior by using field width modifiers to limit the number of characters placed in the arrays by scanf itself, e.g.
if (scanf ("%5s", a) != 1) {
fprintf (stderr, "error: invalid input - a.\n");
return 1;
}
You validate the return of scanf to insure the proper number of conversions have taken place, or you handle the error if they have not.
You prevent reading beyond the bounds of the array by limiting your read and output char loop to only valid characters within the array. You do that by checking the character to be printed is not the nul-terminating character, and when the nul-terminating character is reached, you exit the loop without attempting to print it.
Putting those pieces together, you could do something similar to the following (note j is unused in your code so it is commented out):
#include <stdio.h>
#define N 6
#define K 2
int main (void ) {
char a[N], b[K];
int i = 0/*, j = 0*/;
printf ("enter first word: ");
if (scanf ("%5s", a) != 1) {
fprintf (stderr, "error: invalid input - a.\n");
return 1;
}
for (i = 0; a[i] && i < N; i++)
printf ("%c", a[i]);
putchar ('\n');
printf ("enter second word: ");
if (scanf ("%1s", b) != 1) {
fprintf (stderr, "error: invalid input - b.\n");
return 1;
}
for (i = 0; b[i] && i < N; i++)
printf ("%c", b[i]);
putchar ('\n');
return 0;
}
Example Use/Output
$ ./bin/twowords
enter first word: cats
cats
enter second word: dogs
d
I would strongly caution you to consider reading line-oriented input with a line-oriented input function like fgets. This eliminates many pitfalls for new programmers. The only additional step when using fgets is to recall it reads up-to-and-including the trailing '\n', so you need to trim the '\n' from the string read.
Look things over an let me know if you have further questions.
For the second printf you have to write
printf("%c", b[i]);
As per inputs(abcabc and abc ) you mentioned your are providing to scanf are causing overflow for both the variables a and b,
You should enter string of length 5 for first and 1 for second keeping space for \0 for both the strings
Edit: Also change loop condition from i <= N to i<N or i<sizeof(a).
Please note the loop will print garbage characters past string length if the length of string happens to be less than 5
I see two things that you can do here:
Use another big buffer array that you will load data to, and that copy data to specyfic array. Than you will get max 6 letters of first word in a[], and max 2 letters of second word in b[]. But you will be able to load 2 words.
Scanf specyfic amount of chars like #xing mentiond in comment.
scanf("%6s",word) //general use, not in OP's case
Than when you've got longer word than size that you set up, you will have the rest of input as input in second word.
This question already has answers here:
scanf issue when reading double
(2 answers)
Closed 5 years ago.
sorry for the remedial question. Been troubleshooting to try and find the error and I have come up empty.
I need to write a program that alphabetizes a list of inputs. The first input is the integer value of the number of inputs. Each input ends with a new line character.
int main()
{
int word_total;
char word_in[100][30], t[30];
int i, j;
printf("\nPlease the number of words you wish to sort: \n");
scanf("%d", &word_total);
printf("\nPlease enter a single word at a time. After each word, press return.\n");
for (i = 0; i < (word_total); i++)
{
scanf("%s\n", word_in[i]);
}
for (i = 1; i < (word_total); i++)
{
for (j = 1; j < (word_total); j++)
{
if (strcmp(word_in[j - 1], word_in[j]) > 0)
{
strcpy(t, word_in[j - 1]);
strcpy(word_in[j - 1], word_in[j]);
strcpy(word_in[j], t);
}
}
}
printf("\nSorted list:\n");
for (i = 0; i < (word_total); i++)
{
printf("%s\n", word_in[i]);
}
printf("\n");
}
The problem: the input of words takes word_total + 1. For instance, if word_total = 5, I have to input 6 words. The last word that is input is ignored and not included in the "Sorted list". I can fix the problem by:
for (i = 0; i < (word_total - 1); i++)
{
scanf("%s\n", word_in[i]);
}
but then the "Sorted list" is short one word. I've tried changing "<" to "<=", etc, but haven't found a fix.
Thank you for your help!
The problem seems to be
scanf("%s\n", word_in[i]);
which, due to the "\n", will attempt to read more whitespace following the string (until it finds another non-whitespace; note that any whitespace character actually means any number of whitespace characters; the \n does not match just a single newline as you apparently expect). You should remove the "\n" from the scanf format and eat the newline with a getchar() or similar.
PS: not testing the return value from scanf() is asking for trouble.
This question already has answers here:
If statements not working?
(2 answers)
Closed 7 years ago.
I'm trying to ask a user to enter a string of characters. I want my program to continue scanning in the characters one at a time until it sees the \n character (i.e., when the user presses the ENTER key).
It appears that the code I've written doesn't store the characters to the array for some reason. I know this because the for loop containing the printf() statement doesn't reproduce the characters that are entered into the terminal. My last ditch effort was to print out a[0] in case something was going wrong with my loop, but it still showed that nothing was stored to my character array.
Any explanations? (Please don't suggest that I use the string.h library--I do not wish to use it for my purposes.)
#include <stdio.h>
int main(void)
{
char a[21];
int i;
printf("enter a bunch of characters: ");
for (i = 0; ; i++)
{
scanf("%c", &a[i]);
if (a[i] = '\n')
{
break;
}
}
printf("the size of char array is %d\n", sizeof(a)/sizeof(a[0]));
for (i = 0; a[i] != '\0'; i++)
{
printf("%c", a[i]);
}
printf("%c", a[0]);
return 0;
}
if (a[i] == '\n') { break; }
Modify if statement as above and check.