473,385 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Why can't I assign a character from getchar() into character array?

So I am trying to get a sentence using getchar() and print it out.
I assigned the character I get from getchar() into a char variable and it worked fine.
But when I assigned into character array directly, it looks like the loop never ends and wait for me to input more.

<CODE>

#include <stdio.h>

int main()
{
char a[81];
int i = 0;

printf("Enter a sentence\n");

while( a[i] != '\n')
{
a[i] = getchar();
i++;
}

a[i - 1] = '\0';

printf("%s\n", a);

}

</CODE>

So this code does not work because I used a[i] directly.
Following code works fine.

<CODE>


#include <stdio.h>

int main()
{
char a[81];
int i = 0;
char character;

printf("Enter a sentence\n");

while( character != '\n')
{
character = getchar();
a[i] = character;
i++;
}

a[i - 1] = '\0';

printf("%s\n", a);

}

</CODE>

What's going on???Why can't I just assign it into array ? Why should I go through a variable ?
Jul 29 '15 #1

✓ answered by weaknessforcats

This code:

Expand|Select|Wrap|Line Numbers
  1. while( a[i] != '\n')
  2.  {
  3.  a[i] = getchar();
  4.  i++;
}
doesn't do what you think.
Assume i is 0. Then getchar assigns to a[0]. Then i is incremented so the while loop checks a[1] != '\n'

Unfortunately, a[1] hasn't been initialized yet.

Maybe:

Expand|Select|Wrap|Line Numbers
  1. for( i =0; ( a[i] = getchar()) != '\n'; ++i);
  2.  
BTW: always check for EOF on the return from getchar in case you exhaust the input buffer.

2 2550
weaknessforcats
9,208 Expert Mod 8TB
This code:

Expand|Select|Wrap|Line Numbers
  1. while( a[i] != '\n')
  2.  {
  3.  a[i] = getchar();
  4.  i++;
}
doesn't do what you think.
Assume i is 0. Then getchar assigns to a[0]. Then i is incremented so the while loop checks a[1] != '\n'

Unfortunately, a[1] hasn't been initialized yet.

Maybe:

Expand|Select|Wrap|Line Numbers
  1. for( i =0; ( a[i] = getchar()) != '\n'; ++i);
  2.  
BTW: always check for EOF on the return from getchar in case you exhaust the input buffer.
Jul 30 '15 #2
donbock
2,426 Expert 2GB
Another issue with both of these loops is that the loop condition is tested before the loop body is executed, so the first time through the loop you are testing uninitialized variables.
Expand|Select|Wrap|Line Numbers
  1. while( a[i] != '\n')
  2.     {
  3.     a[i] = getchar();
  4.     i++;
  5.     }
  6.  ...
  7. while( character != '\n')
  8.     {
  9.     character = getchar();
  10.     a[i] = character;
  11.     i++;
  12.     }
One way to properly achieve your aim is to use do-while, where the test occurs after the body executes. (Notice the first loop tests moved i++ into the loop test to account for the problem identified above by @weaknessforcats.)
Expand|Select|Wrap|Line Numbers
  1. do
  2.     {
  3.     a[i] = getchar();
  4.     } while( a[i++] != '\n');
  5.  ...
  6. do
  7.     {
  8.     character = getchar();
  9.     a[i++] = character;
  10.     } while( character != '\n');
However, be aware that do-while is used a lot less often than for or while.

Another issue that neither loop protects the program from a user who types in more than 80 characters.
Jul 30 '15 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Christian Kandeler | last post by:
Hi, if I want to store the string "123456" in a variable of type char, I can do it like this: char s = "123456"; Or like this: char s = { '1', '2', '3', '4', '5', '6', '\0' };
7
by: Chris Wertman | last post by:
I am so lost on this one. Dim Ary as Integer = New Integer(4) {0,1,2,3} FAILS with the error: Array initializer has 1 too few elements. So I try Dim Ary as Integer = New Integer(3)...
12
by: nikNjegovan | last post by:
So i have a tachometer that I can communicated with via UART which gives me a character array of ascii values in the following form: Standard ascii 7 characters including decimal point such that...
9
by: Wondering Wanderer | last post by:
hi, If I declare a character array ( say, char arr ), how do I see the address of the first element of the array ? simply using cout << arr or cout << &arr displays the entire string in the...
3
by: roopa.v1 | last post by:
Hi, How to assign long to character array and later extract it
14
by: Shhnwz.a | last post by:
Hi, I am in confusion regarding jargons. When it is technically correct to say.. String or Character Array.in c. just give me your perspectives in this issue. Thanx in Advance.
8
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. ...
2
by: overdrigzed | last post by:
Hello! I wanted to get the full contents of a character array stored in a struct, i.e. _fields_ = however, ctypes seems to try to return struct.array as a Python string rather than a...
1
by: Sopheap Panha | last post by:
I have tried to find another solution that can output as the code below. It works fine, but it is a bad way to use,because we will be hard if we have more than 10 elements. So can anyone help me how...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.