#include<stdio.h>
#include<string.h>
void main()
{
int entry,i;
printf("\nPlease indicate the number of records you want to enter :\n");
scanf("%d",entry);
char ent[entry][100000];
printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n");
for(i=0;i<entry;i++)
{
gets(ent[i]);
printf("%s",ent[i]);
}
}
The following is a code to accept data of student , first name last name and then score.
main should return int, not void.
int main(void) {
/* ... */
}
scanf("%d",entry);
scanf expects the argument corresponding to the "%d" format specifier to be an int *. Your argument, however, is an int. Perhaps you meant this:
scanf("%d",&entry);
On that note, you should really check the return value of scanf. For all you know, the user didn't enter anything numeric.
if (scanf("%d", &entry) != 1) {
exit(0);
}
In fact, this still allows the user to enter a negative number. Have you ever seen an array of a negative number of items? Seems strange to me, too... I think size_t would be a more appropriate type than int (and as a result, you'll need to use the %zu format specifier)...
Last but not least, gets is deprecated because it makes it impossible to prevent the user from overflowing buffers, which could cause segfaults.
#include <stdio.h>
#include <string.h>
int main(void)
{
size_t entry;
printf("\nPlease indicate the number of records you want to enter :\n");
if (scanf("%zu",&entry) != 1)
{
exit(0);
}
char ent[entry][100000];
printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n");
for(size_t i=0; i<entry; i++)
{
fgets(ent[i], sizeof ent[i], stdin);
printf("%s",ent[i]);
}
}
you should use int main()instead of void main
when you use you should scanf("%d",&entry) instead of scanf("%d",entry),what scanf need is an address.
you shouldn't use gets(),it's dangerous,try fgets()
scanf("%d",entry); //scanf("%d",&entry)
char ent[entry][100000]; //error
you should use malloc to get an array when you can not know the length of an array in compiling time
The error is in scanf use scanf("%d",&entry) instead of scanf("%d",entry);
Suggestion: use int as return type for main
Related
I'm a student and was given this function by our teacher to get user input. It's used for integers but I'm confused why there's a char data type. If someone could explain this function that would be great.
#pragma warning (disable: 4996)
int getNum(void)
{
char record[121] = {0};
int number = 0;
fgets(record, 121, stdin);
if( sscanf(record, "%d", &number) != 1)
{
number = -1;
}
return number;
}
When calling we do this for example:
int age = 0; //we always have to initialize
age = getNum(); //this is how we call the function to get user input
The char record[121] variable is actually an array of characters, otherwise known as a string. It is used here so that, if an erroneous input is given (instead of a valid integer input), then the input stream is still cleared by the fgets() call, which takes in all characters up to (and including) the newline character.
The sscanf function then attempts to extract a valid integer from the read character string and, if it fails, then an error value (-1) is assigned to signal that fact. If it succeeds, it assigns the given input value to number, in the same way that a successful call to scanf("%d", &number) would.
However, just using such a simple scanf() call would potentially leave 'unprocessed' characters in the input stream, which could cause problems for any subsequent input operations (or require the input stream to be cleared).
Using such a technique will also prevent undesired/unexpected effects caused by a user typing extra characters after a valid input. For example, the following (deliberately bad) code will cause a 'surprise' if you enter 1a in response to the first prompt:
#include <stdio.h>
int main()
{
int number = 0, number2 = 0;
printf("Enter first number: ");
scanf("%d", &number);
printf("Enter second number: ");
scanf("%d", &number2);
printf("Given numbers were: %d and %d.\n", number, number2);
return 0;
}
However, using the getNum() function your teacher provided, the following code is much more robust:
int main()
{
int number = 0, number2 = 0;
printf("Enter first number: ");
number = getNum();
printf("Enter second number: ");
number2 = getNum();
printf("Given numbers were: %d and %d.\n", number, number2);
return 0;
}
The program is reading lines from a file with fgets, which uses a string as storage buffer for the line. After that it processes the line to find a string that can be read as an int (%d), checks if that operation went OK, and returns the integer if so.
The function is reading input as text, storing it to the character array record. It then converts that string into an equivalent integer value using sscanf.
This is a bit safer than just using scanf directly - it ensures that if the user types non-numeric input, it's still consumed from the input stream so that it doesn't cause problems later on.
I'm creating a "phonebook" program for school. Basically I have to get a user to input the names and phone numbers of their contacts into two different arrays. I got that part down, but after I have to give the user an option to search the contacts either via name or phone number and I'm running into some issues.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main()
{
int arraysize;
printf("How many phone numbers will you be entering: ");
scanf("%d", &arraysize);
int * phoneNumbers = malloc(arraysize);
char * names = malloc(arraysize);
for (int i = 0; i < arraysize; ++i)
{
printf("Please enter the name of person %d: ", i + 1);
scanf("%s", &names[i]);
printf("Please enter %s's phone number: ", &names[i]);
scanf("%d", &phoneNumbers[i]);
}
char * searchOption;
printf("Would you like to seach via name or phone number? ");
scanf("%s", &searchOption);
if (strcmp(searchOption, "name") == 0)
{
char * searchName;
int element;
bool stop = false;
while (stop = false)
{
searchName = NULL;
printf("\nPlease enter the name you wish to search for: ");
scanf("%s", &searchName);
for (int i = 0; i < arraysize; ++i)
{
if (strcmp(searchName, names[i]) == 0)
{
element = i;
stop = true;
break;
}
}
if (stop = false)
{
printf("\nname not found, please search again!");
}
}
}
I'm pretty sure it's crashing at the strcmp() call but I have no idea why
The problem is, in
scanf("%s", &searchOption);
you're doing it wrong.
You need to
First allocate memory to searchOption pointer (or make it an array).
pass searchOption, not &searchOption to scanf().
Same issue appears for char * searchName; also later in the code.
The crash is not directly caused by the strcmp() call.
This line is at fault:
scanf("%s", &searchOption);
First of all, there is a type mismatch. For %s you have to pass an argument of type char*, not char** as you did. To fix this, remove the take-address (&) operator.
Additionally, you need to allocate memory to scan into. The scanf function doesn't do that for you. As a quick and dirty fix, you can simply make searchOption an array. Replace its declaration with
char searchOption[100];
or such to fix this. You also want to limit the number of characters scanf() attempts to read:
scanf("%100s", searchOption);
so there can't be a buffer overflow.
An even better approach is to use fgets() instead of scanf(). The fgets() function is suited better for what you want to do. Read the manual for how to use fgets().
As Alter Mann said, the same problem occurs a second time further down. You need to repair that, too.
Also i think in strcmp you have used "name" whereas you declared it as names before.If you correct this maybe program works
i am starting to learn C and I have ran into the problem of adding a string input to a 2D array, i am able to get the string input correctly but when i try and add the string element to the array it is not working as expected.When printing the array(which is how i test the program) it will assign each index in the array a single character instead of the entire string.
And here is my code for viewing, thank you very much in advance i appreciate any help that is posted.
#include <stdio.h>
main()
{
char c_array[3][3];
int x;
int y;
int z=10;
int i_user_input;
char c_name[256];
for(x=0;x<=+2;x++)
{
for(y=0;y<=2;y++)
{
printf("\nPlease enter a name to the system:");
scanf(" %s",&c_array[x][y]);
printf("The string is %s\n",c_name);
printf("Please press '1' if you would like to keep entering names\n");
printf("Please press '2' if you would like to print the list of names:");
scanf("%d",&i_user_input);
if(i_user_input==1)
continue;
if(i_user_input==2)
for(x=0;x<=2;x++)
{
for(y=0;y<=2;y++)
{
printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
}
}
}
}
}
The output looks as follows with the sample input 'Penelope!'
c_array[0][0]=P
c_array[0][1]=e
c_array[0][2]=n
c_array[1][0]=e
c_array[1][1]=l
c_array[1][2]=o
c_array[2][0]=p
c_array[2][1]=e
c_array[2][2]=!
When you declare:
char c_array[3][3];
This means that each element of your 2D array is a "char" (a single character); not a "string of characters".
To have each element be a string of characters, you need to declare your array in the following way:
char string_array[3][3][256];
I am not sure this is what you want to do though. Mw feeling is that you want an array of 3 elements where each element is a string. In that case, [3] is hardly enough, your strings will have to be less than two characters (the third being reserved for the terminating zero).
Strings aren't a type. They're a value pattern, like if you say an int stores a multiple of ten, then it ends in 0... If you say an array of char stores a string, then it ends at the first '\0', see? We can store multiples of ten in different kinds of integer variables, and likewise for strings.
Strings are patterns of values, not types. When choosing which integer type we want to use, we consider the range for integers. We choose int for small integer values (less than 32768), long for larger values (less than 2147483648) or long long for values larger than that. As a result, we choose the correct type of integer depending on the multiple of ten we expect. Likewise for strings, we need to make sure we have enough memory for the characters in the string followed by the '\0' at the end.
The character &c_array[x][y] only has enough memory for 0 characters followed by a '\0' at the end; it's only useful for storing an empty string. Perhaps you meant to declare c_array like this:
char c_array[3][3][256];
In this case, scanf expects %s to correspond to an argument of the type char *... but as your compiler will probably warn you, &c_array[x][y] will have the type char (*)[256]. If you want to fix that warning, you'll need to remove the & from your scanf code:
if (scanf("%s", c_array[x][y]) != 1) {
/* XXX: Handle an error here, *
* e.g. by exiting or returning or something */
}
While we're on that topic, you'll notice that I removed the redundant space; %s already performs the functionality that the format directive would perform. I also wrote code to check the return value of scanf, as you should...
Remember how we spoke about choosing the types of integers that we use to store data? One other consideration is whether or not the data we intend to store can be negative. Consider this: In your code, should x and y be able to store negative values? What sense does a negative array index make? It is advisable that all array indexes be declared as size_t. When you use printf to print a size_t value, you'll want to use the %zu format specifier rather than %d.
char c_name[256];
/* ... */
printf("The string is %s\n",c_name);
Now, if the string is stored into c_array[x][y], then what is the point of c_name? That's an unnecessary variable. Use c_array[x][y], instead.
printf("\nPlease enter a name to the system:");
Common implementations will often refrain from printing characters until a '\n' is written; the line is printed all at once rather than character by character. As a result, you might see some strange behaviour such as this line not appearing at the right time. Fix this problem by putting the '\n' on the end of the line, rather than the beginning:
printf("Please enter a name to the system:\n");
... or use puts, which adds a '\n' for you automatically:
puts("Please enter a name to the system:");
... or use fflush, which will write all pending unwritten data even if there is no '\n':
fflush(stdout);
In your code
scanf(" %s",&c_array[x][y]);
printf("The string is %s\n",c_name);
both the statements are wrong.
%s expects a pointer to an array, not a single char. To scan a single char, you need %c format specifier.
c_name, as used in the printf() is uninitialised. Using uninitialised value invokes undefined behaviour.
Solution: To take input element by element, you can do do something like
for(x=0; x<=2 ;x++)
{
printf("Start entering the name, one character at a time\n");
for(y=0; y< 2; y++) //note only '<' here
{
scanf(" %c", &c_array[x][y]); // note the leading space
}
c_array[x][y] = 0; //null termination of array to be used as string
}
If you want to assign a string to each index in the array, then create the array as follows :
#include<stdio.h>
int main(void)
{
char a[2][10];
int i=0;
char temp[20];
for(i=0;i<2;i++)
{
scanf("%s",temp);
strcpy(a[i],temp);
}
printf("%s",a[0]);
return 0;
}
Each string that you enter will be stored in each index of the array.
#include <stdio.h>
#include <string.h>
int main(void){
char c_array[3][3];
int x;
int y;
//int z=10;//unused
int i_user_input;
char c_name[256];
printf("\nPlease enter a name to the system:");
scanf("%255s",c_name);
printf("The string is %s\n",c_name);
printf("Please press '1' if you would like to keep entering names\n");
printf("Please press '2' if you would like to print the list of names:");
scanf("%d", &i_user_input);
if(i_user_input==1)
;
else if(i_user_input==2){
memcpy(c_array, c_name, sizeof(c_array));
for(x=0;x<3;x++){
for(y=0;y<3;y++){
printf("c_array[%d][%d]=%c\n", x, y, c_array[x][y]);
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 3
int main(void){
char *c_array[SIZE][SIZE] = { NULL };
int x;
int y;
//int z=10;//unused
int i_user_input;
char c_name[256];
for(x=0;x<SIZE;x++){
for(y=0;y<SIZE;y++){
printf("\nPlease enter a name to the system:");
scanf("%255s", c_name);
printf("The string is %s\n", c_name);
printf("Please press '1' if you would like to keep entering names\n");
printf("Please press '2' if you would like to print the list of names:");
scanf("%d", &i_user_input);
c_array[x][y] = strdup(c_name);
if(i_user_input==1){
continue;
}
if(i_user_input==2){
int x, y;//local variable
for(x=0;x<SIZE;x++){
for(y=0;y<SIZE;y++){
if(c_array[x][y] != NULL)
printf("c_array[%d][%d]=%s\n", x, y, c_array[x][y]);
}
}
}
}
}
for(x=0;x<SIZE;x++)
for(y=0;y<SIZE;y++)
free(c_array[x][y]);
}
Why not use pointers in you array/matrix?
#include <stdio.h>
#include <string.h>
main()
{
char *c_array[3][3];
int x;
int y;
int z=10;
int i_user_input;
char c_name[256];
for(x=0;x<=+2;x++)
{
for(y=0;y<=2;y++)
{
printf("\nPlease enter a name to the system:");
scanf(" %s",c_name);
new_string = malloc(strlen(c_name)+1)
if (new_string == NULL) {
print("error allocating string\n")
exit(-1);
}
strcpy(new_string, c_name);
c_array[x][y] = new_string
printf("The string is %s\n",c_name);
printf("Please press '1' if you would like to keep entering names\n");
printf("Please press '2' if you would like to print the list of names:");
scanf("%d",&i_user_input);
if(i_user_input==1)
continue;
if(i_user_input==2)
for(x=0;x<=2;x++)
{
for(y=0;y<=2;y++)
{
printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
}
}
}
}
for(x=0;x<=2;x++) {
for(y=0;y<=2;y++) {
free(c_array[x][y])
}
}
}
The code above stores the input string in each cell of the array, if that is your goal.
Note: I have no tried it, so there may be subtle errors. My point is to show you how to use pointers and their equivalence to arrays. Using C without pointers is pointless. :)
Please tell me what is wrong with below code. After executing it is showing
"test.txt has 0 instances of letter 'r'"
`#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fp;
char ch,cmp;
char f[100];
int count=0,tu1,tu2;
printf("Enter the file name\n");
scanf("%s",f);
fp=fopen(f,"r");
printf("Enter the character to be counted\n");
scanf("%c",&ch);
tu1=toupper((int)ch);
while((cmp=fgetc(fp))!=EOF)
{
tu2=toupper((int)cmp);
if(tu1==tu2)
{
count++;
}
}
fclose(fp);
printf("\nFile \'%s\' has %d instances of letter \'%c\'",f,count,ch);
return 0;
}`
Point 1
Always check for the sucess of fopen() before using teh returned file pointer. Add a NULL check for fp after this (below) line of code. If NULL, discontinue the program
fp=fopen(f,"r");
Point 2
Change
scanf("%c",&ch);
to
scanf(" %c",&ch); // mind the ' ' before c
to avoid the trailing newline (\n) stored by previous ENTER key press.
Point 3
As per the man page of fgetc(), the return type is int. Change the data type of cmp from char to int.
Note:
The recommended signature of main() is int main(void)
It is always a good practive to initlize the local variables.
I'm trying to store a few values in a struct object and I want to repeat the prompt until the user types in "yes". I want to use a do-while loop for that. I'm already failing with the read-in of the first "last name". When I type in something, the program just stops (no error). I don't even use the do-while, since I'm not sure if it will work with my while() condition.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
struct employeelist
{
char last[6];
char first[6];
int pnumber;
int salary;
};
int main()
{
struct employeelist employee[5];
char check;
//do
//{
printf("Hello. Please type in the last name, the first name, the personal number and the salary of your employees.\n");
printf("Last name: ");
scanf("%c", employee[1].last);
printf("First name: ");
scanf("%c", employee[1].first);
printf("Personal number: ");
scanf("%d", &employee[1].pnumber);
printf("Salary: ");
scanf("%d", &employee[1].salary);
printf("You have more employess (yes/no)?: ");
scanf("%c", &check);
//}while (scanf("yes"));
return 0;
}
Use %s as your format specifier if you're trying to get a string. You might also want to limit its length to 5, since that's how much space you have for last and first. So that would be %5s. Also, 5 characters is pretty short for a name.
Another comment: arrays in C are zero-based, so employee[1] is the second employeelist in your array. If you want to do this in a loop with an incrementing index, start at 0.
Hi when you read char array you must use scanf("%s", employee[1].last); %s but not %c
What do you think this code does?
scanf("%c", ....
%c indicates that scanf should only read ONE character.
One letter is not going to get you an entire name.
You need to switch to %s for starters.
First of all the first index to work
with will be '0',not 1.
wrong identifier for string,it
should be %s.
If you just want to iterate by
asking y/n then just change the
display message from yes/no to y/n
and also change that strange while
condition to check=='y'||check=='Y'.
The code will actually not work
after 5 iterations because you
initialized only 5 structures of
that type.Why don't you add that in
the loop?