473,320 Members | 1,845 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,320 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 2542
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: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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...

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.