I have made the structure, but I'm stuck at the last point where I have to perform if/else coding. This is my very first program, using some tutorials on web.
The code is below:
#include<stdio.h>
#include<conio.h>
int main()
{
char fName;
char mName;
char lName;
int dob;
int branch;
int brcode;
char * pbprint;
printf("\tWELCOME TO BANK OF KANPUR :: ONE HAND ROLE TO YOUR SUCCESS");
printf("\n\n\n Customer Detail Form");
printf("\n ---------------------");
printf("\n\n\tCustomer Entity ");
printf("\n ");
printf("\n\n\n Customer's First Name : ");
scanf("%s", &fName);
printf("\n Customer's Middle Name : ");
scanf("%s", &mName);
printf("\n Customer's Last Name : ");
scanf("%s", &lName);
printf("\n\n\tDate of Birth ");
printf("\n ");
printf("\n\n\nDate[DD] : ");
scanf("%d", &dob);
printf("\nMonth[MM] : ");
scanf("%d", &dob);
printf("\nYear[YYYY] : ");
scanf("%d", &dob);
printf("\n\n\tBranch Details ");
printf("\n ");
printf("\n\n\nBranch Code : ");
scanf("%d", &brcode);
printf("\n\n\tPrinter ");
printf("\n ");
printf("\n\n\nWould You Like Us To Print Your Passbook [Y/N] : ");
scanf("%s", &pbprint);
// please help how to make if else statement here
// how to make the condition when if I enter yes it should show your
// printing is done else your printing is not done.
getchar();
return 0;
}
You are reading a string from console. If I understood, a simple way is to check only the first char from the string. You can do this:
if ( (pbprint[0] == 'Y') || (pbprint[0] == 'y') )
{
printf("your printing is done");
}
else
{
printf("your printing is not done");
}
The user is usually very creative, so you can choose how smart and versatile your input interface should be.
First of all change your variable declaration from char to char array, as you want strings to be entered. I am considering maximum you will enter 19 characters in strings so you variable declaration will look as below:
char fName[20];
char mName[20];
char lName[20];
char pbprint; // This is just character as you want single character input
You can change your taking character input as below:
printf("\n\n\nWould You Like Us To Print Your Passbook [Y/N] : ");
scanf(" %c",&pbprint); // Notice whitespace in the format string
if((pbprint == 'Y') || (pbprint == 'y')) // now you can do single character comparison
{
printf("Yes");
}
else
{
printf("No");
}
I hope this helps you to take single character input
Issue #1: You need to set aside space to store string data. The char datatype only allocates space for a single character value ('A', 'j', etc.). Strings are sequences of char values followed by a single 0-valued byte, so you need to set aside arrays of char large enough to hold a name plus the 0 terminator.
So, your name variables need to be declared as arrays of char:
#define NAME_LEN 30 // make this as big as you need
char fName[NAME_LEN + 1]; // Add a space for the 0 terminator
char mName[NAME_LEN + 1];
char lName[NAME_LEN + 1];
To read these using scanf, you would write
scanf( "%s", fName ); // note no & operator
The %s conversion specifier expects its corresponding argument to be a pointer to the first element of an array of char. Under most circumstances, an array expression (such as fname in the call above) will automatically be converted to a pointer, so you don't need to use the & operator in this case.
For safety's sake, you should check the result of the scanf call; it will return the number of successful conversions and assignments (0 if none of the conversions are successful), or EOF if it sees an end-of-file or error condition. You should also specify the maximum number of characters to be read within the conversion specifier; otherwise, if you type in more characters than your destination array is sized to hold, scanf will happily attempt to store those extra characters in the memory past the end of your array, leading to anything from corrupted data to a smashed stack to an outright crash:
if ( scanf( "%30s", fName ) == 1 ) // expect one successful conversion and assignment
{
// successfully read fName
}
else
{
// problem during read
}
Unfortunately, the length has to be "hard coded" into the conversion specifier. You can get around this by using some less-than-intuitive preprocessor macros:
#define S2(x) #x // surrounds x with double quotes
#define S1(x) S2(x) // causes x to be expanded before being passed to S2
#define E1(x) x // causes x to be expanded
#define FMT(x) S1(%E1(x)s) // writes a %xs conversion specifier, where
// x is the max length
Then you can write something like
if ( scanf( FMT(NAME_LEN), &fName ) == 1 )
which will expand out to
if ( scanf( "%30s", &fName ) == 1 )
The S2 and E1 macros look redundant, but they are necessary; you want to "expand" the argument x before applying the # operator to it. If we wrote
#define S1(x) #x
#define FMT(x) S1(%xs)
...
if ( scanf( FMT(NAME_LEN), &fName ) == 1 )
it would expand out to
if ( scanf( "%xs", &fName ) == 1 )
which is not what we want.
Issue #2: Simply declaring a pointer does not set aside storage for the thing you are pointing to. The declaration
char * pbprint;
creates the pointer variable pbprint, but it doesn't allocate any memory for the thing we want to point to. In this particular case, if all you want to store is a y or n value, then declare pbprint as a regular char and read using the %c conversion specifier, like so:
#include <ctype.h>
...
char pbprint;
...
if ( scanf( " %c", &pbprint ) == 1 ) // note leading blank in format string
{
if ( tolower( pbprint ) == 'y' ) // convert to lower case for comparison
{
// show print output
}
else
{
// don't show print output
}
}
else
{
// error on input
}
The leading blank before the %c conversion specifier is necessary to skip over any leading whitespace in the input stream; otherwise, you risk picking up a newline character from a previous entry, which isn't what you want here.
We also use the tolower library function (declared in ctype.h) to convert the input character to lower case for comparison. That way we don't have to write distinct branches for lowercase and uppercase letters.
Related
I want the output to print the data that we print. but it is not working as expected and the output is not displaying and it is exiting
#include <stdio.h>
int main() {
char name[20], department[3], section[1];
printf("enter the name of the student:");
scanf("%s", name);
printf("enter your department:");
scanf("%s", department);
printf("enter the section");
scanf("%s", section);
printf("Name:%s \n Department:%s \n Section: %s ", name, department, section);
return 0;
}
Your program has undefined behavior because the arrays are too short and scanf() stores the user input beyond the end of the arrays, especially the last one, section that can only contain an empty string which scanf() cannot read anyway.
Make the arrays larger and tell scanf() the maximum number of characters to store before the null terminator, ie: the size of the array minus 1.
Here is a modified version:
#include <stdio.h>
int main() {
char name[50], department[50], section[50];
printf("enter the name of the student:");
if (scanf("%49s", name) != 1)
return 1;
printf("enter your department:");
if (scanf("%49s", department) != 1)
return 1;
printf("enter the section");
if (scanf("%49s", section) != 1)
return 1;
printf("Name:%s\n Department:%s\n Section: %s\n", name, department, section);
return 0;
}
Note that using scanf with a %s conversion requires that each data item be a single word without embedded spaces. If you want name, department and section to accommodate spaces, which is more realistic for anyone besides Superman Krypton A, you would use %[\n] with an initial space to skip pending whitespace and newlines (or fgets() but in another chapter):
#include <stdio.h>
int main() {
char name[50], department[50], section[50];
printf("enter the name of the student:");
if (scanf(" %49[^\n]", name) != 1)
return 1;
printf("enter your department:");
if (scanf(" %49[^\n]", department) != 1)
return 1;
printf("enter the section");
if (scanf(" %49[^\n]", section) != 1)
return 1;
printf("Name:%s\n Department:%s\n Section: %s\n", name, department, section);
return 0;
}
scanf(" %49[^\n]", name) means skip any initial whitespace, including pending newlines from previous input, read and store and bytes read different from newline, up to a maximum of 49 bytes, append a null byte and return 1 for success, 0 for conversion failure or EOF is end of file is reached without storing any byte. For this particular call, conversion failure can happen if there is an encoding error in the currently selected locale.
The problem is that you have not accounted for the null character. It should work with the following.
char name[20] , department[4] , section[2];
The reason this happens is that C requires an extra character for the null character \0 which tells the program when the string ends.
first of all you should respect the size of string ,so you should either convert section to char or increase the size of that string because you have here the problem of '\0' character...so the rule is : the size of string is the size what you need + 1 for '\0' NULL character
and her is two program i tried to Modification you program for two scenarios :
#include <stdio.h>
int main(){
/// any size you like just respect the NULL character
char name[20],department[4],section[23];
printf("enter the name of the student:");
scanf("%s",name);
printf("enter your department:");
scanf("%s",department);
printf("enter the section");
scanf ("%s",section);
printf("Name:%s \n Department:%s \n Section:%s ", name,department,section);
return 0;
}
and case of char :
#include <stdio.h>
int main(){
char name[20],department[4];
char section;
printf("enter the name of the student:");
scanf("%s",name);
printf("enter your department:");
scanf("%s",department);
printf("enter the section");
///don't forget this space before %c it is important
scanf (" %c",§ion);
printf("Name:%s \n Department:%s \n Section:%c ", name,department,section);
return 0;
}
I watched for a long time and finally found the problem.
This is problem: char section[1];.
You declared the size is too short.
It looks like this after you declared it: section[0] = '\0';.
If you scanf a, the array data like section[0] = 'a';, and then it automatically add '\0' somewhere, so you got a memory leaking.
So replace char section[1]; to char section[2];.
I will not insist in the reasons of the other answers (that state other problems in your code than the one you are asking for) but I'll limit my answer to the reasons you don't get any output before the first prompt (there's no undefined behaviour before the third call of printf if you have input short enough strings to not overflow the arrays --- the last is impossible as long as you input one char, because to input one char you heed at least space for two)
I want the output to print the data that we print. but it is not working as expected and the output is not displaying and it is exiting
stdio works in linebuffer mode when output is directed to a terminal, which means that output is written to the terminal in the following cases:
The buffer is filled completely. This is not going to happen with a sort set of strings.
There is a \n in the output string (which there isn't, as you want the cursor to remain in the same line for input as the prompt string)
As there is no \n in your prompts, you need to make printf flush the buffer at each call (just before calling the input routines) You have two ways of doing this.
Calling explicitly the function fflush(3), as in the example below:
printf("enter the name of the student:");
fflush(stdout); /* <-- this forces flushing the buffer */
if (scanf(" %49[^\n]", name) != 1)
return 1;
configuring stdout so it doesn't use buffers at all, so every call to printf forces a write to the standard output.
setbuf(stdout, NULL); /* this disables buffering completely on stdout */
/* ... later, when you need to print something */
printf("enter the name of the student:"); /* data will be printed */
if (scanf(" %49[^\n]", name) != 1)
return 1;
But use this facilities only when it is necessary, as the throughput of the program is degraded if you disable the normal buffering of stdio.
So, I got this assignment as a student that ask me to create a simple program using C.
This program input only allow you to input only characters A-Z, a-z, and (space).
and the length of the string should be no less than 1 character and no more than 100 characters.
So, I come with the conclusion that I should use if function to validate if the user input the allowed character.
#include <stdio.h>
#include <ctype.h>
int main()
{
char name[100];
scanf("%s",&name);
fflush(stdin);
if (isdigit(name))
^^^^
{
printf("Wrong answers");
getchar();
}
else
....
It was supposed to print "wrong answers" if you input numbers in there, but this program won't run.. It keeps saying :
error C2664: 'isdigit' : cannot convert parameter 1 from 'char [100]' to 'int'
I don't know what this error means.. Is there something I miss? Or am I using the wrong function?
I have also tried
if (((name>='A')&&(name<='Z'))||((name>='a')&&(name<='z')||)((name==' ')))
{
//this print what i want
}
else
{
printf("wrong answers");//this print "wrong answer"
}
but it always print "wrong answers" no matter I input the correct input or the wrong input.
Your help is highly appreciated.
Thank you.
*ps : I am a beginner at programming.
isdigit() takes an int as argument, not a char*:
int isdigit(int c);
You have to use a loop over the string and check each character in it.
Having said that, to achieve:
this program input only allow you to input only characters 'A'-'Z', 'a'-'z', and ' '(space)
you are better off using isalpha().
Try this out:
#include <stdio.h>
#include <ctype.h>
int main()
{
int i = 0;
char name[101], temp;
// take input one character at a time
while(scanf("%c", &temp)){
// stop when newline or carriage return
if(temp == '\n' || temp == '\0' || !isalpha(temp) ){
break;
}
// save character in array
name[i] = temp;
// move to the next position of the array
i++;
}
printf( "%s", temp );
return 0;
}
The problem you're seeing is that you're passing isdigit the wrong type of value - it expects an int, but you're passing it an array of char. You would have to loop over each and every character in your string to check if it's a digit or not.
But that is ultimately not what you're after as you're looking to confirm that the string contains letters or spaces - there are lots of characters that could be entered that aren't classed as digits that would be accepted incorrectly.
What would be the easiest solution for you, is to use the function strspn. It takes a string and returns the length of how many characters match the second parameter. If that length is the same length as your string, you know that it only contains valid characters.
size_t valid;
valid=strspn(name, "abcdefg(fill in with other valid characters)");
if(valid==strlen(name))
{
// Valid name
}
else
{
// Not valid
}
If you need to expand the accepted characters, it's just a simple case of adding them to the 2nd parameter.
OP's code fails as isdigit() test is a single character is a digit (0-9). It does not test a string.
int isdigit(int c);
The isdigit function tests for any decimal-digit character.
In all cases the argument is an int, the value of which shall be
representable as an unsigned char or shall equal the value of the macro EOF.
OP's buffer is too small to save 100 characters read from the user. At least 1 more needed to detect if too many were read and 1 more for a null character to mark the end of a string.
fflush(stdin); has its problems too.
scanf("%s",&name); does not save white-space. The parameter should have been name too. (no &)
Read a line of user input with fgets() which saves the result as a string.
Test if the input meets the criteria.
Read
#define N 100
// No need to be stingy on buffer size reading user input. Suggest 2x
// We need +1 for extra character detection, \n and \0
char buf[2*N + 1 + 1];
fgets(buf, sizeof buf, stdin);
// lop off potential \n
size_t length = strlen(buf);
if (length > 0 && buf[length-1] == '\n') {
buf[--length] = '\0';
}
Test
only characters 'A'-'Z', 'a'-'z', and ' '(space).
for (size_t i = 0; i<length; i++) {
if (!isalpha((unsigned char)buf[i]) && buf[i] != ' ') {
puts("Invalid chracter");
break;
}
}
length of the string should be no less than 1 character and no more than 100 characters.
if (length < 1 || length > 100) {
puts("Input wrong length");
}
Others approaches can be used to disqualify very long inputs. IMO, very long inputs represent an attack and should be handled differently than a simple line that was a bit too long.
if (length < 1 || length > 100) {
if (length + 2 >= sizeof buf) {
puts("Input way too long");
exit (EXIT_FAILURE);
}
puts("Input wrong length");
}
name must have one extra space for the \0 (NUL) character.
So to store 100 characters, its size should be at least 101.
char name[101];
You could first use
fgets(name, sizeof(name), stdin);
to read into name character array.
Note that fgets() will read in the trailing newline (\n) as well which need be removed like
name[strlen(name)-1]='\0';
Then use sscanf(). Like
size_t l=strlen(name);
sscanf(name, "%100[A-Za-z ]", name);
if(strlen(name)!=l)
{
printf("\nInvalid input.");
}
Note the space after the A-Za-z.
The 100 in the %100[A-Za-z] denotes reading at most 100 characters into name. The [A-Za-z ] will make the sscanf() stop reading if a non-alphabetic character which is not a space is encountered.
First read into name. Then store its length in l. Now read everything till a non-alphabet other than a space occurs in name to name itself (thereby modifying name).
Now compare the length of this new string with l. If they are the same. The input is valid as per your need.
You could also use scanf() instead of fgets() like
scanf("%100[^\n]", name);
which instructs to read every character till a \n into name. If this is used, no \n will added at the end of name unlike the case with fgets().
Now I would like to point out some mistakes in your code.
scanf("%s",&name);
will lead to errors. Correct one is
scanf("%s",name);
as the second argument here must be an address and since an array name in C decays into its base address, just name would do instead of &name.
As others have pointed out, using fflush() on stdin is undefined and must be avoided.
If you are trying to clear the input buffer till the next newline (\n), you could do
int ch;
while((ch=getchar())!='\n');// && ch!=EOF)
The argument of isdigit() must be a char and not a character array (type char [100] if size is 100).
And if is a statement and not a function.
I'm just practicing C and I would like to make a simple Login program with a username and a password... here is my code:
int main(){
char uname, passwd;
printf("Enter your username: ");
scanf("%c", uname);
printf("Enter your password: ");
scanf("%c", passwd);
printf(" \n");
if (uname == "waw" && passwd == "wow"){
printf("You have logged in\n");
} else {
printf("Failed, please try again\n");
}
return 0;
}
And then I got this error when I try to compile it
log.c: In function ‘main’:
log.c:7:10: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%c", uname);
^
log.c:9:10: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%c", passwd);
^
log.c:13:14: warning: comparison between pointer and integer
if (uname == "waw" && passwd == "wow"){
^
log.c:13:33: warning: comparison between pointer and integer
if (uname == "waw" && passwd == "wow"){
^
1) Don't read (scan) into a char. You need a string. Use format specifier %s instead of %c
2) Use strcmp to compare string values
Try this:
#include <stdio.h>
int main(){
int res;
char uname[40]; // char arrays instead of single char
char passwd[40];
printf("Enter your username: ");
res = scanf("%39s", uname); // Set a maximum number of chars to read to
// 39 to avoid overflow
if (res != 1) exit(1); // Error on stdin. End program
printf("Enter your password: ");
res = scanf("%39s", passwd);
if (res != 1) exit(1); // Error on stdin
printf(" \n");
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if ((strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0)){
printf("You have logged in\n");
} else{
printf("Failed, please try again\n");
}
return 0;
}
There is no string data type in C programming language. Strings in C are represented as array of characters.
In C, char is a data type to represent a character. So, all you need to do is declare a array of char data type to represent a string in C. Each element in that array will hold a character of your string.
Also, operators in C like ==, !=, +=, + are defined for build-in data types in C and since, there is no operator overloading in C, you can't use these operators with your C-String as C-Strings are not build-in data type in C programming language.
Note: C-Strings are actually Null-terminated array of char data types. That means, last character in any C-String in C will be used to store a Null Character ('\0') which marks the end of the string.
The Header file <string.h> has predefined functions that you can use to operate on C-String(Null-terminated array of char data type). You can read more about it over here.
So, your program should look like:
#include <stdio.h>
#include <string.h>
#define CSTR_MAX_LEN 100
int main()
{
char uname[CSTR_MAX_LEN+1]; //An extra position to store Null Character if 100 characters are to be stored in it.
char passwd[CSTR_MAX_LEN+1];
printf("Enter your username: ");
scanf("%s", uname);
printf("Enter your password: ");
scanf("%s", passwd);
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if ((strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0)){
printf("You have logged in\n");
} else{
printf("Failed, please try again\n");
}
return 0;
}
Remember, the correct format specifier to handle C-Strings are %s in C programming language. So, i have to change your scanf() function call. Also, i have used strcmp() function which is declared in header file <string.h> (i have included this header file in the above program). It returns numeric zero if strings match. You can read more about it above here. Also, have a look at strncmp() which is safer version of strcmp(). Also, remember that it can lead to undefined behavior if you try to access any array out of it's bound. So, it would be good idea to include checking in your program. As, someone included in their answer you can change my scanf() function call to:
scanf("%100s", uname);
It avoids to read more than 100 characters in array uname as it is allocated only to store 100 characters(excluding the Null character).
This is how you can do it with milkstrings
tXt ask(tXt prmp) {
printf("%s ?",prmp) ;
return(txtFromFile(stdin)) ; }
void main(void) {
tXt user = ask("user") ;
if ( strcmp(txtConcat(user,"/",ask("password"),NULL),"waw/wow") == 0)
printf("You have logged in\n");
else
printf("Failed, please try again\n");
}
First of all, you have declared uname and passwd as single characters, but you want to read strings. So you need to define the maximum length for each one and declare them as following:
char [X] uname; //where X is the maximum length for uname, for instance 25
char [Y] passwd; //where Y is the maximum length for passwd, for instance 20
Accordingly, your scanf() function should then be modified to :
scanf("%s", uname);
scanf("%s", passwd);
Apart from that, you need strcmp() to compare a string with a value. Change your if statement to :
if ( (strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0) ) {
printf("You have logged in\n");
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. :)
I'm following a tutorial on youtube and was doing a dice generator.
It basically print out 3 dice result and sum out the dice result.
After which, the user will look at the sum, and based on the sum, the user going to guess whether the next roll is going to be higher,lower, or the same.
Below is my code, suppose, when I typed 'yes', it should be doing the code inside the if statement. However, it went straight to the else statement. Can someone please tell me what's wrong?
int answer;
int guess;
int diceRoll4 = 0;
printf("Would you like to guess your next dice? Y/N \n");
scanf(" %c", &answer);
if (answer == 'yes' ){
printf("What is your guess?\n");
printf("please key in your number \n");
scanf(" %d", &guess);
if (guess > diceRoll4 ){
printf(" You got it wrong, too high!");
}
else if (guess < diceRoll4){
printf(" You got it wrong, too low!");
}
else {
printf("You got it right");
}
}
else{
printf("Thanks for playing");
}
First of all, answer should be an array of chars in order to hold a string. Change
int answer;
to
char answer[10]; //Or any other reasonable size
Secondly, since you want to scan a string and not a character, change
scanf(" %c", &answer);
to
scanf("%9s", answer);
The 9 will scan a maximum of 9 characters (+1 for the NUL-terminator at the end), thus preventing buffer overflows.
I've removed & as %s expects a char* while &answer will give a char(*)[10]. Name of an array gets converted into a pointer to its first element char*, exactly what %s expects. The above scanf is thus equivalent to
scanf("%9s", &answer[0]);
Thirdly, comparing two strings using == compares pointers and not the actual content in them. Use strcmp from string.h instead. It returns 0 when both its arguments hold the same content. Change
if (answer == 'yes' ){
to
if (strcmp(answer, "yes") == 0){
Double quotes are used to denote a NUL-terminated string(char*), which is exactly what strcmp expects, while single quotes, as in your code, is a multi-character literal whose value is implementation-defined.
'yes' is a multi-byte character whose behaviour is implementation-defined.
What you probably want is to read and compare a single char:
if (answer == 'y' ){
or read a whole string and compare:
char answer[128];
scanf("%s", answer);
if ( strcmp(answer,"yes") == 0 ){
...
}
Notice that I changed the type of answer and used %s to read a string.
If you do not want to read in a string, but only a single char where the user can answer either Y or N, you should change int answer; to char answer;. You can then go on using your original scanf()-call. You will still need to change
if (answer == 'yes')
to
if (answer == 'Y')
If you want the user to either type in y or Y you could user toupper() from ctype.h and change your if-condition to if (toupper(answer) == 'Y').
To test the equality you have to use strcmp. If the returning value is 0 it means that they are equal.
if (strcmp(answer, "yes") == 0) {
// ...
} else {
// ...
}
Notes:
Using just answer == 'yes' it test the equality of pointers not value. This is the reason why enters only in else.
Because answer is int you have to change to an array
char answer[15]
As #Sathya mentioned you are reading just a char %c for reading a string you have to use %s
scanf("%s", answer);
Instead of 'yes' which is multi-character character constant change to "yes" that is an array of char with \0 at the end, more informations here.
this line:
if (answer == 'yes' ){
has several problems.
1) the definition of 'answer' is 'int' but the scanf is inputting a single character
2) answer could be compared with 'y' or 'n' but not to a array of char.
3) since the scanf only input a single char
and you/the user input 'yes',
only the first character was consumed,
so the 'es' are still in the input buffer
4) note the the single character could be anything, except white space.
the leading space in the format string would consume any white space.
so the user could input say 'y' or 'Y'
these are different characters
however, using the toupper() macro from ctypes.h
would mean only a 'Y' would need to be compared
5) if you decide to read a string,
then 'answer' needs to be a character array,
say: char answer[10];
and the scanf needs to have a max length modifier
on the associated "%s" input/conversion parameter
so as to avoid the user overflowing the input buffer
and the comparison would be via the strcmp() function
6) always check the returned value (not the parameter value)
from scanf to assure the operation was successful
7) diceRoll4 and guess can never be a negative number
so the variable definitions should be unsigned
and the associated scanf() for guess should use
something like "%u"
8) on the printf() format strings, always end them with '\n'
so the sting will be immediately displayed to the user,
otherwise, they will only be displayed
when a input statement is executed or the program exits