I'm just starting out with C. I wrote some very basic code for practice, its supposed to read keyboard input into an array, output the length of longest line and then print it.
Theres a function to read the input, I want it to print out each character as it is assigned to the array each time, but it does not work. It prints some strange looking characters.
I did look for "array print garbage" . but didn't find an answer.
int getline(char line[])
/*
This function 1) Reads a line of input until a '\n',
2) Returns the length of the line and
3) Saves the line in the array "line[]"
*/
{
int c,i;
i=0; // The character count
printf("Enter characters:\n");
while((c=getchar())!='\n') // Reads input until it hits a '\n'
{
line[i]=c;
i++;
printf("char %d = %c \n ",i,line[i]);//
Why doesn't this "printf" work right? It prints a strange character at the second placeholder
}
printf("you typed %d characters.\n",i); //Outputs the number of characters typed
return i;
}
You're printing line[i] after you've incremented i. So you're always printing the element after the one you've just set, which is usually garbage.
Put the line
i++;
at the end of your while loop.
Related
I am having a c program which print letter by letter of the word. I referred this program from this link
https://www.tutorialgateway.org/c-program-to-print-characters-in-a-string/. If I run this program in online c compiler this gives the exact result, but not working in turbo c++
#include <stdio.h>
int main()
{
char str[100];
printf("\n Please Enter any String : ");
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++)
{
printf("The Character at %d Index Position = %c \n", i, str[i]);
}
return 0;
}
This program doesn't through any error, but I don't know why this program doesn't print the result.
Try fgets(str, 100, stdin) instead of scanf(). This is the normal way to read a line into a buffer. When I used scanf() I only got part of the output because it will stop reading a string at a space.
IDK what is your output, but here is mine:
Please Enter any String : Hell got loose
The Character at 0 Index Position = H
The Character at 1 Index Position = e
The Character at 2 Index Position = l
The Character at 3 Index Position = l
This is normal, due to this:
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
this is taken from scanf.
EDIT:
Just for the fun, you can do this using scanf
scanf("%[^\n]",str);
this will replace \n newline with '\0'.
NOTE: #Joshua's answer is safer, if you want to know why just google why I shouldn't use scanf()
Trying to take strings as input and place it in 2d array. Why is this given code showing different behavior. The last for loop "arr[i][j]" is not printing the string.It is not even printing a character also.
Why this code does not work.only this code.Not a new way to write it
This code takes input just fine(or at least the way needed.each row a single string no white space)And when a short string is stored remaining are filled with null after carriage return. When the arr[] is passed in last for loop everything seems fine only when arr[][] is passed ,the problem arises.But again arr[][] is initialized as arr[1][0] then arr[2][0] so should not it work!
#include <stdio.h>
#include <stdbool.h>
int main(void){
int i,j,m;
scanf("%d",&m);
char arr[m][50];
for(i=0;i<m;i++){
for(j=0;j<50;j++){
printf("please enter a string");
scanf("%s",&arr[i][j]);
/*j is always 0. arr[i] takes string without space and store ending with null*/
break;
}
}
//Everything fine upto this,including storing a small continuous string in arr[i](where i<50) and null terminating*/
for(i=0;i<m;i++){
for(j=0;j<50;j++){
printf("%s\n",arr[i][j]);
break;
}
}
}
You program has several issues, like using wrong format specifier:
scanf("%s",&arr[i][j]);
arr[i][j] is a character and you are using %s format specifier. If you want your program should take string as input, you just need to do:
scanf("%s",arr[i]);
Since, you have given the size 50 characters, put a restriction in scanf() to not to read more than 49 characters (the remain one character space is for null terminating character) like this:
scanf("%49s",arr[i]);
^^
Beware with this, it does not discard the remaining input from input stream when the input characters are more than 49 and the remaining characters will be consumed by consecutive scanf() call.
If you want to drop the extra input which wasn't consumed by scanf(), one way of doing it is to read and discard the extra input using a loop, like this:
int c;
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
In case if you have any doubt on how this will discard the extra input, I would suggest first go through getchar().
Putting all these together, you can do:
#include <stdio.h>
int main(void){
int i,m;
scanf("%d",&m);
char arr[m][50];
for(i=0;i<m;i++){
printf("please enter a string");
scanf("%49s",arr[i]);
int c;
while((c = getchar()) != '\n' && c != EOF) // <=== This loop read the extra input characters and discard them
/* discard the character */;
}
for(i=0;i<m;i++){
printf("%s\n",arr[i]);
}
return 0;
}
EDIT
The below edit is because OP updated question and added - Why this code does not work.only this code.Not a new way to write it
Above in my answer, I have already stated that you are using wrong format specifier in the scanf(). In this part of your code:
for(i=0;i<m;i++){
for(j=0;j<50;j++){ // <====== Nested for loop
printf("please enter a string");
scanf("%s",&arr[i][j]);
// since the nested loop is supposed to run 50 times, assuming you are trying to read character by character and using %s format specifier
break;
// the nested loop will break in the first iteration itself unconditionally, do you really need nested loop here!
}
}
Check the inline comments. Hope this might give an idea of the mistakes you are doing.
Seems that you want to read string character by character using scanf(). If this is the case than make sure to take care of null terminating character because, in C, strings are actually one-dimensional array of characters terminated by a null character '\0'.
You can do:
#include <stdio.h>
void discard_extra_input() {
int c;
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
}
int main(void){
int i,j,m;
printf ("Enter number of strings: ");
scanf("%d",&m);
discard_extra_input();
char arr[m][50];
for(i=0;i<m;i++){
printf("please enter string number %d: ", i+1);
for(j=0;j<49;j++){
scanf("%c",&arr[i][j]);
if (arr[i][j] == '\n') {
//need to add null terminating character manually
arr[i][j] = '\0';
break;
}
}
if (j==49) {
// In case where the input from user is more than 50 characters,
// need to add null terminating character manually.
arr[i][j] = '\0';
// discard the extra input when input from user is more than 50 characters.
discard_extra_input();
}
}
for(i=0;i<m;i++){
for(j=0;j<50 && arr[i][j]!='\0';j++){
printf("%c",arr[i][j]);
}
printf ("\n");
}
return 0;
}
The code is self explanatory except one thing - call to discard_extra_input() function after first input from user scanf("%d",&m);. Reason -
Look at the statement:
scanf("%c",&arr[i][j]);
the %c format specifier will consume the leftover newline character '\n' from the input stream due to the ENTER key pressed after first input by the user (number of strings input from user). Hence, in order to discard it, calling discard_extra_input() function. In the other place it has been used to discard the characters when user entered string of size more than 49.
Hope this helps.
I know the code. But looking for specific ans. Where the problem lies with the code
The problem is here:
scanf("%s",&arr[i][j]);
and here:
printf("%s", arr[i][j]);
This is the specific answer you are looking for.
%s won't do any bound checking. It adds the characters starting from the memory location arr + i * m + j to arr + i * m + j + (length of input) + 1 (one extra char for the additional null character that scanf appends). Take a sample input. Assume an arbitrary starting address for arr and do the maths.
Also consider any writes beyond the allocated space for arr leads to undefined behavior.
Similarly printf("%s", arr[i][j]); will try to start reading from the address arr[i][j] till it finds a null character. It would usually lead to crash of the code because if your string has ascii characters, the address would be too low to point to any valid user-mapped memory.
If your code is working, its mostly because you already have a UB in your scanf.
Get a pen and paper and do some dry runs
This is a pretty simple problem buddy. You've got the idea right actually, that you need to use 2d array to store strings. Just that the usage is slightly wrong.
First of all let me tell you how 2d arrays need to be used to store in c. In your 2-D array, you've got rows and columns. Say, row represented by i and columns by j, i.e, each row arr[i] contains j elements. So in your context, each row arr[i] contains each string of upto 50 chars. So scanf should be just for arr[i]. And you need to loop with for, m times to accept m strings.
Same applies to printing as well.
Here is the working code:
#include <stdio.h>
#include <stdbool.h>
int main(void){
int i,j,m;
printf("\nenter m value:");
scanf("%d",&m);
char arr[m][50];
for(i=0;i<m;i++){
printf("\nplease enter a string no %d: ", (i+1));
scanf("%s",arr[i]);
}
printf("\nthe strings are: \n");
for(i=0;i<m;i++){
printf("\n%s\n",arr[i]);
}
}
And the output in case you want to cross check:
OUTPUT:
enter m value: 3
please enter a string no 1: qwerty
please enter a string no 2: asdfgh
please enter a string no 3: zxcvbn
the strings are:
qwerty
asdfgh
zxcvbn
I want a code such that I enter some strings one-by-one (by pressing enter) and display it.
for example;
Input
abc
def
Output
abc
def
also I want this input to be in a array so that I can select any character
from the array whenever I want. For example: s[1][1] gives 'e'.
I have writen a code for this problem.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j, n, m;
scanf("%d%d", &n, &m);
char a[n][m];
for (i = 0; i<n; i++)
scanf("%s", a[i]);
for (i = 0; i<n; i++) {
printf("%s", a[i]);
printf("\n");
}
}
But for this code my input/output goes like this:
Input
ab
cd
Output
abcd
cd
Can anyone tell where am I going wrong?
You have not shown the input value of n and m in the question. But from the input and output string shown, it seems that char array a[i] does not have the enough space for terminating null-character \0. When you give format specifier %s, scanf() automatically adds a terminating null character at the end of the stored sequence. I tried your code with input 2 for both n and m and I am getting the output as you are getting:
$ ./a.out
2 2
ab
cd
abcd
cd
Give the value 4 to m and the output is:
2 4
ab
cd
ab
cd
When using scanf() for string input, it is good to add check for max character modifier that is 1 less than the length of the input buffer. So, if the size of input buffer is 4 then you can do
scanf("%3s",a[i]);
With this, the scanf() will read not more than 3 characters in a[i] and will add \0 at the fourth location of a[i]. Beware with this, it does not discard the remaining input from input stream and they will be consumed by consecutive scanf() call.
If you want to drop the extra input which wasn't consumed by scanf, one way of doing it is to read and discard the extra input using a loop, like this:
int c;
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
You can add it after scanf() reads data from input stream, like this:
for(i=0; i<n; i++) {
scanf("%3s", a[i]); // assuming the size of a[i] is 4
int c;
while((c = getchar()) != '\n' && c != EOF) // <=== This loop read the extra input characters and discard them
/* discard the character */;
}
This will work fine for the input that does not contain any whitespace characters. If your input contain any whitespace character, it may not behave as expected. Hence, I would suggest you to read about fgets() which gives you better control for string input.
Check this: fgets
and this: How to read from stdin with fgets()?
you are working with a 2D array of char:
char a[n][m];
but keep in mind the value for the 2nd index should be 1 character longer than the length of the string you wish it to allow room for the \0 byte. (all C strings must be null terminated)
This means char a[n][m]; can contain up to n strings, each string with maximum length of m-1 bytes.
char exampleStr[] = {"char count"}; //for example contains 11 characters (not 10)
|c|h|a|r| |c|o|u|n|t|\0| //note nul char is appended
Another common problem when reading user input in a loop is failure to remove any unwanted newlines, which can cause the loop to behave poorly. Following is an example of how to read a user specified number of strings ( using fgets() instead of scanf() ), each with a user specified length: (also removing unwanted newlines ( \n ) in the process)
For readability, the following example replaces n & m with lines & maxLen.
int main(void)
{
int lines, maxLen, i=0;
printf("Enter number of lines:");
scanf(" %d", &lines);
printf("Enter maxLen line length:");
scanf(" %d", &maxLen);
char line[lines][maxLen+2]; //+2 to allow for trailing newline and null
fgets(line[i], maxLen, stdin);//consume anything left in stdout
printf("Enter up to %d characters and hit return:\n%d) ", maxLen, i+1);
for(i=0;i<(lines);i++)
{
fgets(line[i], maxLen, stdin);
line[i][strcspn(line[i], "\n")] = 0; // clear newline
printf("Enter up to %d characters and hit return:\n%d) ", maxLen, i+1);
}
return 0;
}
All strings in C must be terminated with the null character \0, print knows this and prints all character UP TO that sign. You should make all of your strings 1 character longer than the words you plan to fit in them and fill them with 0 (0 is the integer value of \0) in the start to avoid this problem.
I am new to C programming. And I was doing a practice, and the question goes like this: Use the ?: operator and the for statement to write a program that keeps taking the characters entered by the user until the character q is accounted.
And here is the program I wrote:
#include <stdio.h>
main()
{
int x, i=0;
for (x = 0; x == 'q'? 0 : 1; printf("Loop %d is finished\n",i))
{
printf("Enter q to exit!!!\n");
printf("Please enter a character:\n");
x=getc(stdin);
putc(x,stdout);
++i;
}
printf("\nThe for loop is ended. Bye!");
return 0;
}
The problem is: every time I enter a "non-q" character, the loop seems to run twice.
I don't know what is wrong with my program.
Please help!
When you enter a non-q letter, you also hit Enter, which is read in the second loop.
To make the loop only run once per input, use fgets() to read an entire line of input at once, and check if the input string matches your expectations.
When you type a and then press Enter, the newline character becomes part of the stdin stream. After a is read, the next time you execute x=getc(stdin), the value of x is set to \n. That's why two iterations of the loop get executed.
The loop runs twice because when you enter a non-q character, you actually enter two characters - the non-q character and the newline '\n' character. x = getc(stdin); reads the non-q character from the stdin stream but the newline is still lying in the buffer of stdin which is read in the next getc call.
You should use fgets to read a line from the stream as others have suggested and then you can process the line. Also, you should specify the return type of main as int. I suggest the following changes -
#include <stdio.h>
int main(void)
{
int x, i = 0;
// array to store the input line
// assuming that the max length of
// the line is 10. +1 is for the
// terminating null added by fscanf to
// mark the end of the string
char line[10 + 1];
for (x = 0; x == 'q'? 0 : 1; printf("Loop %d is finished\n", i))
{
printf("Enter q to exit!!!\n");
printf("Please enter a character:\n");
// fgets reads an input line of at most
// one less than sizeof line, i.e.,
// 10 characters from stdin and saves it
// in the array line and then adds a
// terminating null byte
fgets(line, sizeof line, stdin);
// assign the first character of line to x
x = line[0];
putc(x, stdout);
++i;
}
printf("\nThe for loop is ended. Bye!");
return 0;
}
When you enter a character, say 'x' and press enter, you actually input two characters, which are 'x' and '\n' also known as newline(when you hit enter). The '\n' becomes part of the input stream and the loop is executed for it as well.
Also, try inputting "xyz" and hit enter, the loop will be executed 4 times. For each 'x', 'y', 'z', and '\n'.
If you want the code to work one time for every input, use the function gets.
#include <stdio.h>
main()
{
int i=0;
char x[10];
for ( ; x[0]!='q'; printf("Loop %d is finished\n",i) )
{
printf("Enter q to exit!!!\n");
printf("Please enter a character:\n");
gets(x);
i++;
}
printf("\nThe for loop is ended. Bye!");
return 0;
}
In this code we declared x as an string, the gets() function reads the whole line we entered, then in the condition part of the for loop, we check whether the first character of the string is 'q' or not.
My program scans from input and prints all the capital letters used.
Im trying to print the original input from stdin at the end of my program too.
But when i use printf, it seems to skip the first part of the input expression, printing the remaining stuff in my character array. Please help me see where the problem lies. -comments in code-
#include <stdio.h>
int main(void){
char input[81];
int letters[91];
int i;
//initialize arrays input and letters
for (i = 0; i < 90; i++) letters[i] = 2;
for (i = 0 ; i < 80; i++) input[i] = 'a';
i = 0;
//reads into input array until EOF
while((scanf("%c",input)!= EOF)){
//checks input for characters A-Z
if((input[i]>= 'A' && input[i]<= 'Z'))
letters[input[i]] = 1;
}
//prints capital letters from input that occur at least once
for(i = 'A'; i < 'Z'; i++){
if (letters[i]==1)
printf("%c", i);} // this output works fine, the scan worked??
//print blank line
printf("\n\n");
// print input
printf("%s\n", input); //This is where the incorrect output comes from.
return 0;}
does my original input change? why?
did my input not get scanned correctly in the first place?
please respond quickly!
Here:
while((scanf("%c",input)!= EOF)){
you're only ever reading characters into input[0]. This is fine for what you're doing for letters, but obviously when you try to print out input, it's not going to work as you expect.
When you fix it, you'll also need to remember to add a terminating \0 after the last input character.
The scanf loop reads your input one character at a time, and stores that one character in input[0]. When the scanf loop is completely finished, input[0] contains the last character read, and the rest of input is untouched.
To repair, you need to include i++ at the end of the scanf loop.
By the way, it would be clearer (and more efficient) to fill the input buffer with a single call to fgets then loop through the input buffer with: for (i=0; buf[i]!='\0'; i++) { ... }
You must do
while((scanf("%c",&input[i])!= EOF))
{i++;}
instead of this
while((scanf("%c",&input)!= EOF))
{}
What you are doing is scan the character into the address of the first element int the array everytime, hence it gets overwritten again and again. Remaining part of the input[] array is not being accessed, and hence does not change