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 3 years ago.
Improve this question
I'm new to C,and want to write a simple program that takes a user input and prints it out a specific amount of times back to them.
#include <stdio.h>
#include <stdlib.h>
int main() {
char* str[100];
int *p = malloc(sizeof(int) * 10);
int amount;
*p = amount;
int i;
printf("\nType anything!\n");
scanf("%s", str);
printf("\nHow many times?\n");
scanf("%d", amount);
for (i=0; i<=amount; i++) {
printf("%s", str);
}
return 0;
}
It works fine,until after pressing entering the amount of times,when the program crashes with the Fish shell saying "fish: “./a.out” terminated by signal SIGSEGV (Address boundary error)".
Address boundary error tells me that maybe I haven't allocated memory for something,but how would I go about doing that? I've tried using malloc with a pointer pointed at amount but it doesnt seemed to have solved anything.
It's remarkable how many issues there are in such a short chunk of code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[100];
int amount;
printf("\nType any word!\n");
if (scanf("%99s", str) != 1)
{
fprintf(stderr, "Failed to read a string\n");
return(EXIT_FAILURE);
}
printf("\nHow many times?\n");
if (scanf("%d", &amount) != 1)
{
fprintf(stderr, "Failed to read an integer\n");
return(EXIT_FAILURE);
}
for (int i = 0; i < amount; i++)
{
printf("%s\n", str);
}
return 0;
}
The signature of main() is a full prototype.
The type of str is corrected (or, at least, changed and made usable).
The code related to p and malloc() is not needed.
The variable i is moved into the for loop (assumes a C99 or later compiler; if not available, what you had was OK).
Change "anything" to "any word" because %s skips white space and then reads non-spaces up to the next white space.
Limit the amount of input to prevent overflows.
Report if there's a problem reading the string and exit.
Fix the scanf() to pass &amount (key change).
Check for success reading amount and report failure and exit.
Define i in the loop control (C99).
If the user requests one copy, only print one copy (change <= to < — that's an idiomatic C loop now).
Output newline after each word. There are other ways to present the data, including the one chosen originally, but you should at least end the output with a newline.
Related
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 2 years ago.
Improve this question
I am a newbie to C programming. I am trying to solve a question using scanf in loop, but the problem is that scanf is only running once inside the loop. My code is:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
int x=0;
scanf("%d", &n);
for (int i=1; i<=n; i++)
{
char stat[3];
scanf ("%s", stat);
if (strcmp(stat, "X++")==0)
x++;
else if (strcmp(stat,"++X")==0)
x++;
else if (strcmp (stat, "--X")==0)
x--;
else if (strcmp(stat, "X--")==0)
x--;
}
printf ("%d", x);
return 0;
}
Why is the scanf running only once even when n is 2, 3 or anything else?
This may be because the value of the variable n is destroyed by out-of-bounds write.
Your buffer stat don't have insufficient size to store 3-character string because there are no room to store terminating null character.
Increase buffer size and limit number of characters to read for safety.
Checking if reading is successful will make it safer.
char stat[3];
scanf ("%s", stat);
should be
char stat[4];
if (scanf ("%3s", stat) != 1) return 1;
The problem is about taking input of strings x number of times using an array of pointers. x is the value entered by the user. I wrote the following code for the same. But the program is taking only x-1 inputs.
I have inserted fflush(stdin) because I think the scanf is consuming an enter first but I don't know from where.
I have tried using gets but with no use.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
//code to take input in an array of pointers
int x,i,j,length;
char ch[50],*t;
printf("How many names you want to sort:\n");
scanf("%d",&x);
char *names[x];
char *p;
printf("Enter the names:\n");
for(i=0;i<x;i++)
{
fflush(stdin);
scanf("%[^\n]s",ch);
length = strlen(ch);
p = (char *)malloc((length+1) * sizeof(char));
strcpy(p,ch);
names[i] = p;
}
return 0;
}
Why bother with complex format strings if you don't have to? Use fgets.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void err(const char * msg) {
fprintf(stderr, msg);
exit(1);
}
int main()
{
int x,i;
char ch[50];
printf("How many names you want to sort:\n");
if(!fgets(ch, 50, stdin)) err("Error reading line");
if(sscanf(ch, "%d",&x) != 1) err("Could not read integer");
// Better than using VLA
char **names = malloc(x*sizeof(*names));
if(!names) err("Error allocating names");
printf("Enter the names:\n");
for(i=0;i<x;i++) {
if(!fgets(ch, 50, stdin)) err("Error reading line");
ch[strcspn(ch, "\n")] = 0; // Remove newline
if(!(names[i] = strdup(ch))) err("Error duplicating string");
}
for(int i=0; i<x; i++)
printf("name %d: %s\n", i, names[i]);
}
Whenever a function has a return value that may indicate an error you should ALWAYS check it, and here that is the case for malloc, fgets, strdup and sscanf and. Read the documentation to find out what it actually returns to see how to check for errors. sscanf returns the number of successful assignments, and the other three returns a pointer which is NULL on failure.
You wrote in the comments that you are learning from the book "Let us C". A better fitting title would be "How to not code C". I've had a quick look at it and, it is really really bad. Apart from teaching very outdated C, it also teaches very bad habits in general, and many of the things you can read is completely WRONG. Actually, the majority of questions about C can be traced to that book, or at least could have. Two prime examples is that it consistently avoids very important stuff, such as error checking functions like scanf and malloc. I have not read every line, but I think it does not even mention how to error check scanf even once. It also uses the function gets which is not only deprecated but completely removed from newer C standards because it is so dangerous. It also says that you can modify a string literal, which is undefined behavior in C.
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 4 years ago.
Improve this question
I got the task to scan 10 numbers that will later on be converted into characters. The problem is that I don't get why there is an infinite loop if I don't enter 0. I got the task right with array but I am interested why does this happen in example bellow.
#include <stdio.h>
#include <stdlib.h>
int main() {
/**
* for the example enter numbers: 8 5 12 12 15 23 15 18 12 4 -> helloworld
*/
char n;
// message needs to be 10 numbers long.
for (int i = 1; i <= 10; i++){
// enter message in numbers.
scanf("%d", &n);
// check if it is 0. if it is, end the message.
if(n == 0) {
printf("\nEnd of the message!");
break;
// if number is not 0, add 64 to transform to char.
}else {
n = n + 64;
// print the char.
printf("%c ", n);
// print the i, that doesn't increment.
printf(" -> i:%d\n", i);
}
}
return 0;
}
You are using
char n;
...
scanf("%d", &n);
You cannot use %d with char. You should change n to an int or use %c for scanf and printf.
int n;
...
scanf("%d", &n);
OR
char n;
...
scanf("%c", &n);
You are using a char to read an int. The scanf fails and input remains in the buffer and so scanf keeps on reading the same value again and again resulting in an infinite loop.
So, declare n as an int.
It is a good practice to check the return value of scanf so that you will know if the input has been read properly.
The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure
The problem is with the scan!
scanf("%c", &n);
%d for ints, %c for chars, %s for strings, %f for floats!
scanf("%d", &n) reads an int into n. Since n is a char this results in the 3 bytes that appear after n being overwritten by the scanf. In your case the variable i was allocated within memory that overlaps those 3 bytes and so each call to scanf modifies the variable i resulting in a potentially infinite loop. Use %c to read in a character rather than %d.
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 6 years ago.
Improve this question
I want to read n integers from user during execution and the numbers are separated by spaces. It would be the best to be received as an array. For input 1 22 3 445 3, the result is, array[0]=1, array[1]=22 and so on. I have to do it in C. Can't use
scanf("%d %d %d", &var1, &var2, &var3);
because, I don't know how many such numbers would be inserted. The value of n would be read from user just before reading this data.
enum { MAX_NUMBERS = 1000000 }; // Choose appropriate upper bound
int n;
if (scanf("%d", &n) == 1 && n > 0 && n < MAX_NUMBERS)
{
int array[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &array[i]) != 1)
…process error — terminate loop?…
}
…use array…
}
You can read multiple numbers with scanf() using a loop as shown. You've no idea whether they were all presented on a single line, or each was on its own line, or whether there were many blank lines between successive numbers (or any permutation of all these possibilities).
The scanf() family of functions basically do not care about newlines — it is hard to force them to do so. When you care about line-based input, use fgets() or POSIX function getline() to read a line and sscanf() — or other string parsing functions — to process the line.
I'm assuming support for C99 with VLA (variable length arrays). The principles are the same without that support — the mechanics are a little different (and there are multiple options for how to do it).
Use fgets() and then strtok() with atoi().
Take the numbers as a string.
Here is one way to do it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char numbers[100];
int myn[100];
printf("Give me numbers..\n");
fgets(numbers,100,stdin);
const char s[2] = " ";
char *token;
token = strtok(numbers, s);
int i=0;
myn[i]=atoi(token);
while( token != NULL )
{
i++;
printf( " %s\n", token );
token = strtok(NULL, s);
myn[i]=atoi(token);
}
printf("You gave me: ");
for (int j=0; j<i; j++){
printf ("%d, ", myn[j]);
}
return(0);
}
The above C program does exactly what you want. At the for loop, it prints to the screen the numbers you gave from keyboard. The "problem" would be much easier by using enter instead of spaces between the numbers.
Click on the links, to see very useful details about the functions used.
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
while i am running the above title is appearing as error
#include <stdio.h>
int main()
{
int i;
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s",name);
while(name[i]!="\0")
{
i++;
if(name[i]==" ")
{
strcpy(b[i],name[i]);
printf("copied name: ");
scanf("%s",b[i]);
}
}
}
while i am running this it is showing this error why? warning: comparison between pointer and integer.
"\0" is a string, '\0' is a character. As you comparing a character, you need the latter.
Also, as pointed out by chqrlie, there are many other issues - you need to check your compiler warnings/errors and fix them all. For example,
name[i]==" " is wrong with the same reason.
where is b declared?
where is i initialized??
There are many errors/ warnings in your code.
It should be '\0'. Not "\0";
You have not declared b[];
Initialize i=0;
Instead of strcpy, you can use another method which is shown in below code.
Also, you should not use scanf in last line. You should use printf. scanf is used to take input from user. printf is used to print the results.
Code-
#include <stdio.h>
int main()
{
int i=0,n;
char name[20],b[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s\n",name);
while(name[i]!='\0')
{
b[i]=name[i]; // to copy from name[] to b[]. Instead of strcpy
i++;
}
printf("copied name: ");
for(n=0;n<=i;n++)
{
printf("%c",b[n]); // to show the copied result.
}
printf("\n");
return 0;
}