I am getting this error whenever I run my code in visual Studio:
#include <stdio.h>
#include <ctype.h>
int main() {
char username[10];
printf("Enter Username: ");
scanf_s("%[^\n]", &username);
while (isupper(username)) {
if (username == '-') {
printf("Username cannot contain UpperCase Letters");
}
}
}
Error Image
I don't think you can pass whole array to isupper. Also if you don't want to return anything instead of int main() use void main() or just return 0 in the end or when you want to end after your program executed successfully. As for using scan_s or scanf or getline or whatever I won't say anything because its a different matter and your syntax of scanf_s is certainly wrong.
Also following code will not check for any buffer overflow (not a good practice, you will see even though we gave size 20 char array, this code will work even for larger input which is certainly not a good thing). So you can either limit the size of input or better to read an entire line via fgets() (or getline() if available) and parse the string yourself.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char username[20];
printf("Enter Username: ");
// scanf("%[^\n]", username); <--- Instead of this
scanf_s("%20c", username, 20); // <----Try Using this
int i=0;
while (i<strlen(username)) {
if (isupper(username[i])) {
printf("Username cannot contain UpperCase Letters\n");
return 0;
}
i++;
}
return 0;
}
My first guess would be that your while is an endless loop, try to do it like this:
int i;
for(i=0; i<strlen(username);i++){
if(isupper(username[i])){
printf("Username cannot contain UpperCase Letters");
}
}
Related
It's just a code to receive user inputs in C program, but fails to do so and accepts null space as input. I have tried fgets() as well and the same thing keeps happening. Please advice on how to fix.
#include <math.h>
#include <stdio.h>
//#include <string.h>
#define len 16
int main(void)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,i=0,j=0;
printf("enter the number of cards:");
n = getchar();
//scanf("%d",&n);
int c1[len][n],card[len][n];
char buf[len];
printf("Enter card number:");
gets(buf);
system("Pause");
return (0);
}
"...code to receive user inputs in c program, but fails to do so and accepts null space as input..."
The reasons your existing code has problems is covered well in the comments under your post.
Consider a different approach: Define the following:
char inBuf[80] = {0};//
int numCards = 0;//Pick variable names that are descriptive (n is not)
int cardNum = 0;
bool isnum;
Then use it in conjunction with printf() etc.
printf("enter the number of cards:");
if(fgets(inBuf, sizeof(inBuf), stdin))//will read more than just a single char, eg. "12345"
{
int len = strlen(inBuf);
isnum = true;
for(int i=0;i<len;i++)
{
if(!isdigit(inBuf[i]))
{
isnum = false;
break;
}
}
if(isnum)
{
numCards = atoi(inBuf);
}
else
{
printf("input is not a number\n"
}
}
printf("Enter card number:");
if(fgets(inBuf, sizeof(inBuf), stdin))
{
...
Repeat variations of these lines as needed to read input from stdin, with modifications to accommodate assignment statements based on user input i.e. an integer (this example is covered), a floating point number, a string (eg. a persons name)
Although there is more that you can do to improve this, it is conceptually viable for your stated purpose...
This question already has answers here:
Issue with main arguments handling
(3 answers)
Closed 6 years ago.
I am learning C on my own but this code which seems right to me doesn't works right
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
main()
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %s", name);
if ( (name=='luv') || (name='pranav') )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
I want the correct code to run only if I enter name as luv or pranav but instead what is happening is that no matter whatever name i type it is running the code under else and i am not able to figure out the reason.
I am using codeblocks as compiler.
You cannot compare strings using ==, to compare strings, one has to use strcmp()
strcmp() returns 0 when the strings are same, other wise it returns the difference of those two strings,
So essentially, your code would become,
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for the strcmp() function
main()
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %s", name);
// strings are given inbetween double quotes
// characters are given inbetween single quotes
if ( !(strcmp(name, "luv")) || !(strcmp(name, "pranav")) )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
NOTE:
1) Use the standard definition of main()
int main(void) //if no command line arguments.
2) Check the return of functions like scanf().
Lots of mistakes in the code.
I am trying to fix and show:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // to use strcmp
int main(void) // int and void added
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf("%19s", name); // no space before % and 19 to limit input
if ( !strcmp(name,"luv") // " instead of ' , and strcmp with operator !
|| strcmp(name,"pranav") == 0 ) // instead of ! you can use == 0
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
main() is not a standard signature. You should use standard int main(void) unless you have some special reason to use non-standard signature.
'luv' and 'pranav' are multiple-character character constant, which have implementation-defined values. You should use string literals and strcmp() function.
name='pranav' is an assignment, and you cannot assign to what is converted from arrays, so this will emit compile error.
You should limit the length to read in order to avoid buffer overflow.
Try this:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %19s", name);
if ( (strcmp(name, "luv") == 0) || (strcmp(name, "pranav") == 0) )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
remove #include <conio.h> and getch(); if they are not supported.
Two problems:
Single quotes are used for character constants, not string constants. You need to use double quotes for those.
Strings can't be compared with ==. What you're actually doing is comparing the address of the first element of name with a character constant. Even if you fixed the quotes on the constant, you'd be comparing the address of name with the address of a string constant, which are not the same. To compare strings, you use strcmp, which compares each character in the string.
So what you want is this:
if ( (strcmp(name,"luv") == 0) || (strcmp(name,"pranav") == 0) )
You'll also need to #include <string.h> to use strcmp.
I have a typical question it's not that how can I scan spaces using scanf but how to scan the initial spaces entered in a string
This is what I've done:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char a[10];
scanf("%d",&n);
scanf(" %[^\n]",a);
printf("%d",strlen(a));
return 0;
}
and when I run the program with following input:
aa bb//note there are two spaces before initial a
and the output is 6 but there are 8 characters i.e, 2 spaces followed by 2 a's followed by 2 spaces and then lastly 2 b's
I eve tried an own function.. but alas! the length is 6. Here's my function:
int len(char a[101])
{
int i;
for(i=0;a[i];i++);
return i;
}
What I think is that the initial 2 spaces are being ignored...or I might be wrong. It'd be great if someone could explain why the length of string is 6 and how can I make it 8 or accept all the 8 characters I mentioned above.
EDIT: this is my actual code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,N,j,k;
char **ans,s[101];
scanf("%d",&N);
ans=(char **)calloc(N,sizeof(char*));
for(j=0,i=0;i<N;i++)
{
scanf(" %[^\n]",s);
printf("%d",strlen(s));
ans[i]=(char*)calloc(strlen(s),sizeof(char));
for(k=0,j=((strlen(s)/2)-1);j>=0;j--,k++)
{
ans[i][k]=s[j];
}
for(j=strlen(s)-1;j>=strlen(s)/2;k++,j--)
{
ans[i][k]=s[j];
}
}
for(i=0;i<N;i++)
{
printf("%s\n",ans[i]);
}
scanf("%d",&i);
return 0;
}
OP code should work as posted.
OP comments true code is using scanf(" %[^\n]",a); which fully explains the problem: the space in the format is consuming leading white-space.
To address other issues with scanf(), see following.
fgets() is the right tool.
Yet if OP insists on scanf()
how can I scan spaces using scanf but how to scan the initial spaces entered in a string?
char buf[100];
// Scan up to 99 non\n characters and form a string in `buf`
switch (scanf("%99[^\n]", buf)) {
case 0: buf[0] = '\0'; break; // line begins with `'\n`
// May want to check if strlen(buf)==99 to detect a long line
case 1: break; // Success.
case EOF: buf[0] = '\0'; break; // stdin is closed.
}
fgetc(stdin); // throw away the \n still in stdin.
The issue i believe is that you need to be getting length from a Pointer to the array not the array itself.
Try this, this code worked for me.
int ArrayLength(char* stringArray)
{
return strlen(stringArray);
}
I am unable to take two inputs strings simultaneously in C on Ubuntu. It shows the wrong output.
Simple program:
#include <stdio.h>
main()
{
char s1[20],char s2[20],printf("\nEnter job:");
scanf("%[^\n]s",s1);
printf("Enter hobby:");
scanf("%[^\n]s",s2);
}
Output:
Enter job:student
Enter hobby:
student
It does not allow the input of a second string. How can I overcome this bug?
If you want to allow embedded spaces, modify the scanf formats this way:
#include <stdio.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
scanf("%99[^\n]%*c", job);
printf("Enter hobby:");
scanf("%99[^\n]%*c", hobby);
printf("%s,%s", job, hobby);
return 0;
}
But be aware that empty lines will not be accepted by this scanf format. The linefeed will stay in the input stream, the second scanf will fail too and job and/or hobby will have indeterminate contents, letting printf invoke undefined behavior.
Is is much more reliable to use fgets() and strip the '\n'.
#include <stdio.h>
#include <string.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
if (!fgets(job, sizeof job, stdin))
return 1;
job[strcspn(job, "\n")] = '\0';
printf("Enter hobby:");
if (!fgets(hobby, sizeof hobby, stdin))
return 1;
hobby[strcspn(hobby, "\n")] = '\0';
printf("%s,%s", job, hobby);
return 0;
}
I know this question gets asked a hundred times over, and I've scoured all of the possibilities, but I guess I'm not adept enough to know where this problem lies. I'm programming a program where I need to fill a struct with data (ints and strings). The first time I tried it it skipped over everything but the first one, but I didn't panic since I remembered from class I needed to use fflush(stdin) to overcome this. Websites I've searched vote against use of fflush(stdin), since it has undefined behaviour. They say using getchar() would eat the extra newline, thus fixing the problem. Hence my code:
int manNode(){
Item *p;
int helper;
p = (Item*)malloc(sizeof(Item));
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
scanf("%u",&helper); //selecting an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
getchar(); //I've just put getchars everywhere for safety.
p->entrytype = helper-1;
helper = 0;
printf("Vul een naam in:\n");
scanf("%s", p->name); //this one fills in fine
getchar();
printf("Vul een vaknaam in: \n");
scanf("%s", p->course); //this one gets skipped if I type more than one letter in the last scanf()
getchar();
printf("Vul een starttijd in:\n"); //From here on out everything gets skipped
p->start = getTijd();
checkTijd(p->start);
printf("Vul een eindtijd in: \n");
p->end = getTijd();
checkTijd(p->end);
I know it's a bit messy, but focus on the scanfs and getchars. getTijd() also has a couple of scanfs in it that scan for integers, they also get skipped. I don't know where to go from here. (The code isn't incomplete, the rest is just irrelevant)
you can define a new getchar
#include <stdlib.h>
#include <stdio.h>
#define getchar(x) (scanf("%c", x))
int main ()
{
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
return 0;
}
update: this may be a better approach
#include <stdlib.h>
#include <stdio.h>
void work_to_do()
{
#define getchar(x) (scanf("%c", x))
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
#undef getchar
}
int main ()
{
work_to_do();
return 0;
}
to solve the scanf newline ignorance and getchar (but still scanf ignores whitespace)
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#define __getchar() (read(2, NULL, 1)) // 2 stands for standard error, we can make the user enter a character.
void work_to_do()
{
char y[10];
__getchar();
scanf("%s", y);
printf("got %s\n", y);
__getchar();
}
int main ()
{
work_to_do();
return 0;
}
and it's good to take a look at this:
Read space-separated values from file
scanf works as documented. Also, there is nothing wrong with scanf so long as its function is understood.
I created a copy of your code and distilled it to highlight what you want to do. You will need to fill-in the rest yourself.
In this code you need to enter a digit and press enter. Then enter a string and press enter, etc. Note. the fflush(stdout) statement is part of the standard C implementation per K&R. The fflush forces the contents of the buffer out to the console. This flushing makes for a reasonable user/computer dialog.
#include <stdio.h>
main()
{
char string[100];
int helper;
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
fflush(stdout);
scanf("%d",&helper); //select an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
printf("Vul een naam in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een vaknaam in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een starttijd in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een eindtijd in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
}
This code ran on Eclipse with a Microsoft C Compiler.
Also, let me emphasize that if you enter: 1 AAA BBB CCC DDD and press enter then scanf will get executed five times. In this example, the code would run to completion!
So you need to trace your code logic (in this case a straight line) to see how the scanfs are invoked based on what data is entered.
Hope this helps. Please ask if more questions.