While loop with tables C - c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 30
int main()
{ char c, y, input[N];
int X, i=0, j;
printf("Give displacement\n");
scanf("%d",&X);
printf("Give chars\n");
while(((c=getchar()) !=EOF) && (i<N-1)){
input[i]=c;
i++;
}
input[i]='\0';
j=0;
for(j=0; j<=i-1; j++){
if (isalpha(input[j])){
if (isupper(input[j]))
y=(input[j]-'A'+X)%26+'A';
else
y=(input[j]-'a'+X)%26+'A';
putchar(y);
}
}
return 0;
}
hey all. well, this code doesnt seems to works as it should. It skips 2 positions at the table instead of one. Which makes the program unusable since i need a table of 30 positions. I think that the problem is in the while loop, but i really cant find it. Any help would be apprecieted.
Thanks in advance.

After the call to scanf, there's a newline left in the input buffer. That newline becomes the first character read by getchar.
To get the newline out of the buffer, add a separate call to getchar right after the scanf call:
scanf("%d",&X);
getchar();
That will give you the additional character you're missing.
Also, as mentioned in the comments, c should be defined as an int instead of a char, because getchar returns an int. Otherwise, the test for EOF will always be false.

if you want 30 characters you have to define N as 31
[0 - 29] + '\0'
In your first while loop i believe that the second test is wrong:
Use it like this:
while(((c=getchar()) !=EOF) && (i<=N-1)){
input[i]=c;
i++;
}

Related

How to scan input from terminal and add to array?

as a homework assignment for my computing 1 college course, my professor has given me the task of having the user input a string of characters into the terminal, taking that string, adding it into an array, then printing the array and printing the array backwards. I think that I know of a way to print the array backwards, however, I cannot come up with a way to read from the terminal and add the characters from the terminal to an array. I have tried doing the following:
char ch;
for (int i = 0; i <= 80 || str[i] == '\n'; ++i) {
scanf_s("%c", &str[i]);
}
I am wondering if someone could explain to me why this section of code does not operate as expected, and if someone could give me some other ideas to try. Thank you.
You are using scanf_s with %c specifier incorrectly.
Please take notice of compiler warnings, there is a size argument missing.
Microsoft's scanf_s is not a direct replacement for scanf.
Unlike scanf ... scanf_s ... requires the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.
scanf_s("%c", &str[i], 1);
You might also want to filter out any newline which may have been left in the buffer, with
scanf_s(" %c", &str[i], 1);
notice the added space.
Why your code is showing this type of behaviour...
use scanf instead of scanf_s
the conditions you have provided in the for loop are wrong
#include <stdio.h>
int main()
{
char ch;
char str[1000];
int i;
for (i = 0; i <= 80 ; i++)
{
scanf("%c", &str[i]);
if(str[i]=='\n')
{
str[i]='\0';
break;
}
}
printf(str);
}
I could show you the same task in simple manner. I have tried to answer your question in your way. That's why it may seem complicated.
#include <stdio.h>
#define MAX 25
int main()
{
char buf[MAX];
fgets(buf, MAX, stdin);
printf("%s\n", buf);
return 0;
}
fgets- Reads until new line character encountered or maximum limit of character array.

While loop not exiting with `while(x!='\n')`

Why is this while loop not exiting ?
I want to input a series of number from users and then use them one by one for further processing. I do not have the size of numbers list. Can someone please tell me how to do this ?
#include<stdlib.h>
#include<stdio.h>
int main()
{
int x;
scanf("%d",&x);
while(x!='\n')
{
printf("%d",x);
scanf("%d",&x);
}
return 0;
}
Example:
Input:
3 5 6
Output:
3 5 6
Actual Output:
3 5 6
but loop doesn't exit
The %d conversion specifier never stores the \n into the buffer. It reads up to the \n in the buffer and leaves it there. So, this is essentially an infinite loop.
You may need to use a format specifier like %c which actually reads and stores the \n.
Although, if I may suggest, try to make use of getchar(), which reads the next character from the standard input and returns the value as an int. However, for an input of digits, you need to parse and store the integer and/or float value accordingly, but it will certainly provide you more flexibility.
What about this?
while(scanf("%d", &x) != EOF) {
printf("%d",x);
if (getchar() == '\n') break;
}
Why not use argv and strtol ?
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
int i = 0, x;
for(i = 1; i < argc; i++) {
x = strtol(argv[i],NULL,10);
printf("%d\n",x);
}
return 0;
}
while(scanf("%d",&x) != EOF) {
printf("%d",x);
}
...would do it. Don't ignore scanf returns. The reason your code is looping is you're really comparing x against decimal value of 10 ('\n'). Also, please remember that you asked scanf to give you integers and that's what it gives you, it will not give you newlines, even if it could.
Edited, so that I added comparison to EOF specifically.
You need to remember that scanf scans a stream, in this case the input stream, it will not return until that stream is done.
You should really use strings and sscanf() for what you want to do.

While loop go through irrespective of conditions in C

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void){
int corX = 0;
do{
printf("Please enter number X:\n");
scanf("%d",&corX);
} while(!(isdigit(corX) && corX>1 && corX<80));
printf("You entered X as: %d\n",corX);
return 0;
}
Hi! The code above should check if the entered value is an integer and fit to the range. If not, program should ask again. Unfortunately, it does not work in this way. Whatever I write, loop always go through and in a result I receive entered number for numbers and 0 for other signs. Could somebody explain, what I am doing wrong?
there seems to be a problem in your while condition. I rewrote it and I get what I think is the behavior you wanted (ask for input when input smaller 1 or greater 80)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
int main(void){
int corX = 0;
do{
printf("Please enter number X:\n");
scanf("%d",&corX);
} while( ( corX<1 || corX>80 ) && clean_stdin() );
printf("You entered X as: %d\n",corX);
return 0;
}
edit: I did not check my initial post careful enough. The checking for isdigit is not needed at all as you already are using %d in scanf, I removed it completely from the while condition. As quick fix for the infinite loop problem I added the clean_stdin() function that is mentioned in the accepted answer of this post How to scanf only integer and repeat reading if the user enter non numeric characters? that #Gangadhar mentioned in his comment and which I recommend for reading (which also I should have done before posting)

Empty string ends for loop

What's wrong in the below program (What's happening here)? It should break the for loop after the user inserts empty string (presses only ENTER), but in my case it ends in endless for loop. I tried what is in the comments with no success.
#include <stdio.h>
#include <string.h>
struct S {
char str [10];
};
int main(void)
{
int n;
struct S strings [10];
for (n = 0; n < 10; n++) {
# fflush(stdout);
scanf("%s", strings[n].str);
if (strlen(strings[n].str) == 0)
break;
# getchar();
}
printf("done");
return 0;
}
When I replace scanf with gets(strings[n].str); done is never printed. How would you fix it?
This sample solution works. Is there a difference in comparison to my code?
The enter key is not empty string, it is an ascii character or rather two characters a CR and LF (on Windows).
You shouldn't use strlen to find out if the input is empty. As others have said, when you press ENTER you get one or two characters sent to you.
You could instead check the first character in the string and see if it is '\n' or '\r'
scanf returns exactly what you've input... i.e. a crlf pair I'd imagine!
The problem with using scanf is that it expects something, not an empty string. You solve this by using e.g. fgets instead of scanf:
if (fgets(strings[n].str, sizeof(strings[n].str), stdin))
{
/* You got a string, it will contain the newline! */
}

C Prints One Char More Without Value

I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts to give the value.
#include <stdio.h>
int main() {
char ch;
int t;
while(t < 3){
scanf("%c\n", &ch);
printf("%c - %d\n", ch,ch);
t++;
}
}
http://i54.tinypic.com/2mdqb7d.png
Variable t is not automatically initialized to 0 by compiler. So You need to initialize t with 0. If printf doesn't print immediately it means the data is buffered. If you want to see immediatley you may consider flushing stdout right after printf.
I saw this several times, and don't know the root cause, but solution that works is:
scanf("\n%c", &ch);
It probably has something to do with buffered end of line character.

Resources