My program is not accepting simple string in c using getchar - c

int count0=0,count1=0,cnt=0;
char str[200];
char ch;
ch= getchar();
while(ch!='\0')
{
str[cnt]=ch;
cnt++;
}
str[cnt]='\0';
printf("%s",str);
output expected :
shubham
output:
Your code didn't print anything.
input:
shubham

You are just accepting one character, you should replace while() with do-while().
int ch;
do
{
ch= getchar();
if(ch == EOF)
{
str[cnt] = '\0';
break;
}
else
str[cnt] = ch;
cnt++;
}while(ch != '\0');
The above loop should fix the issue that you are facing. You need to enter NULL terminator using ctrl+# at the end of the string.

A while loop is fine. Simply put the getchar() in it.
Use int ch rather than char ch as getchar() typically returns 1 of 257 different values: 0 - 255 and EOF(a negative value). EOF indicates end-of-file (or rare input error).
size_t count = 0;
int ch;
// test to insure not too many read, ch == EOF? ch == end-of-line?
// | | |
while (count < sizeof str - 1 && (ch == getchar()) != EOF && ch != '\n') {
str[count++] = ch;
}
str[count] = '\0';
puts(str);
Or perhaps one prefers a for() loop?
size_t count;
for (count = 0; count < sizeof str - 1; count++) {
int ch == getchar();
if (ch == EOF || ch == '\n') {
break;
}
buf[count] = ch;
}
buf[count] = '\0';
puts(str);

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i=0, j=0,T;
T=getchar();
int ch;
for(i=0; i<T ;i++)
{
int cnt=0;
char str[200];
while ((ch = getchar()) != '\n' && ch != EOF)
{
str[cnt] = ch;
cnt++;
}
str[cnt]='\0';
printf("\n%s",str);
}
return 0;
}
**
here str is storing almost everything
space, \n,
**
expected output:
shubham
shubh
output:
shubham
shubh
shubham
shubh
input:
shubham
shubh
*/

Related

Why the functions doesn't return new line with replaceable keywords?

Hey just doing some exercises in c, one is saying to replace tabs in the input string with any other characters , i restrict myself to only using getchar(), no gets() fgets() etc..., as my learning book didn't catch it yet, so i tried to not break the flow, the code below just printf() the same line it receives, can you please examine why ?
#include <stdio.h>
int main(){
char line[20];
char c;
int i = 0;
printf("Enter name: ");
while ( c != '\n'){
c = getchar();
line[i] = c;
++i;}
while (line[i] != '\0')
if (line[i] == '\t')
line[i] = '*';
printf("Line is %s \n", line);
return 0;}
c, which is used in c != '\n', is not initialized at first. Its initial value is indeterminate and using is value without initializng invokes undefined behavior.
You are checking line[i] != '\0', but you never assigned '\0' to line unless '\0' is read from the stream.
You should initialize i before the second loop and update i during the second loop.
Return values of getchar() should be assigned to int to distinguish between EOF and an valid character.
You should perform index check not to cause buffer overrun.
Fixed code:
#include <stdio.h>
#define BUFFER_SIZE 20
int main(){
char line[BUFFER_SIZE];
int c = 0;
int i = 0;
printf("Enter name: ");
while ( i + 1 < BUFFER_SIZE && c != '\n'){
c = getchar();
if (c == EOF) break;
line[i] = c;
++i;
}
line[i] = '\0';
i = 0;
while (line[i] != '\0'){
if (line[i] == '\t')
line[i] = '*';
++i;
}
printf("Line is %s \n", line);
return 0;
}

I have encountered segmentation error when attempting to replace the tabs from entered strings with spaces

I have experienced some problem with segmentation when I'm learning through C, my aim is to swap the tabs in the program with spaces:
I have used the get_line template and modified the code to suit the situation. Here is the whole coded solution:
#include <stdio.h>
#define MAXLINE 1000
char line[MAXLINE];
char detabline[MAXLINE];
int get_line(void);
int main(void){
int len;
int i;
int nt = 0;
extern char detabline[];
extern char line[];
while ((len = get_line()) > 0){
for (i = 0; i < len; ++i){
if (line[i] == '\t'){
printf("%s", " ");
}
else{
printf("%s", line[i]);
}
}
}
return 0;
}
int get_line(void){
int c, i, nt;
nt = 0;
extern char line[];
for (i = 0; i < (MAXLINE - 1) && (c = getchar()) != EOF && ((c != '\t') || (c != '\n')); ++i){
line[i] = c;
}
if (c == '\n'){
line[i] = c;
++i;
}
else if (c == '\t'){
++nt;
}
line[i] = '\0';
return i;
}
The problem is to locate which memory isn't allocated correctly. I may have some redundant code in the solution by the way.
regarding:
for (i = 0; i < (MAXLINE - 1) && (c = getchar()) != EOF && ((c != '\t') || (c != '\n')); ++i){
this expression:
(c != '\t')
will result in no tab character ever being in the line[] array.
this expression:
(c != '\n')
will result in no newline character sequence ever being in the line[] array.
then, due those expressions, the line[] array will not be updated (ever again) when a tab or a newline is encountered due to those expressions causing an early exit from the for() loop
The following proposed code:
cleanly compiles
performs the desired functionality
and now, the proposed code:
#include <stdio.h>
#define MAXLINE 1000
char line[MAXLINE];
int main(void)
{
int i = 0;
int ch;
while ( i< MAXLINE-1 && (ch = getchar()) != EOF && ch != '\n' )
{
if ( ch == '\t')
{
line[i] = ' ';
}
else
{
line[i] = (char)ch;
}
i++;
}
printf( "%s\n", line );
}
Post a comment if you want further details about the proposed code.

why my code is printing output for input text containing more than 10 characters?

#include<stdio.h>
main() {
char ch, a[10];
int i = 0;
printf("enter text,press <return> to end!\n");
while (ch != '\n') {
ch = getchar();
a[i] = ch;
i++;
}
i = i - 1;
a[i] = '\0';
printf("%s", a);
}
here i declared an array 'a' of maximum size 10.I used a while loop to read characters and place them in array 'a' and finally the code prints the text i have entered
I've done a little more checking in this version.
#include <stdio.h>
#define STRLEN 10
int main(void) { // correct signature
char ch, a[STRLEN+1]; // room for terminator
int i = 0;
printf("Enter text, press <return> to end!\n");
while(i < STRLEN && (ch = getchar()) != EOF && ch != '\n') // more checks
a[i++]=ch; // excludes newline
a[i]='\0'; // terminate string
printf("%s\n",a); // added newline
return 0;
}
This is really unsafe as you have a statically declared array of 10 chars. If the user enters a 11th char you will encounter buffer overflow. You should check i in your while too:
while(ch!='\n' && i < 9) {
ch=getchar();
a[i]=ch;
i++;
}
a[i]='\0';
printf("%s",a);

skip whitespaces but not newline in c without break and continue

I want to read characters from user and assign the chars to char array. But I want to skip whitespaces except \n(newline char). The loop would be end when press \n. How can I do it ? I cannot use break and continue. Thank you for all appreciated answers.
char *
get_set(char *set)
{
char inset[10];
char ch = ' ';
int i = 0;
while(ch != '\n'){
inset[i] = scanf(" %c", &ch);
i++;
}
set[strlen(inset)] = '\0';
return (set);
}
char *get_set(int size, char *set){// size : size of set as buffer size
char ch;
int i;
for(i = 0; i < size-1 && (ch=getchar()) != '\n'; ){
if(!isspace(ch))
set[i++] = ch;
}
set[i] = '\0';
return set;
}
You can use getchar:
while (((ch = getchar()) != '\n')) {
if(!isspace(ch))
inset[i++] = ch;
}
getchar reads the next character from stdin and returns it as an unsigned char cast to an int, or EOF on end of file or error.
once try these,
char *
get_set(char *set)
{
char inset[SETSIZ];
char ch = ' ';
int i = 0;
while(ch != '\n'){
if(ch!=32)// ASCII 32 for whitespaces
inset[i] = scanf(" %c", &ch);
i++;
}
set[strlen(inset)] = '\0';
return (set);
}

C Random, having problems

void getS(char *fileName){
FILE *src;
if((src = fopen(fileName, "r")) == NULL){
printf("%s %s %s", "Cannot open file ", fileName, ". The program is now ending.");
exit(-1);
}
//char *get = " ";
int c = 1;
char ch = 'x';
while(ch!=EOF) {
ch = fgetc(src);
if(ch == '\n') c++;
}
fseek(src, 0, SEEK_SET);
int random = rand() % c;
int i = 0;
for(i = 0; i < random; i++){
while(ch != '\n'){
ch = fgetc(src);
}
}
do{
ch = fgetc(src);
if(ch != '\n' && ch != EOF){
printf("%c", ch);
}
}while(ch != '\n' && ch != EOF);
printf("%c", '\n');
fclose(src);
}
So this is my function that grabs a file and prints out a random word in the file if each word is separated by a new line.
Question 1:
Why is the random having preference to the first 2 words?
Question 2: How would I make it so I can use this function multiple times without doing the printf("%c", '\n'); because if I don't have that in the end the previous function call just overwrites the old one.
Thanks in advance, I've been asking a bit today thanks for all the help stackoverflow! :)
P.S. using srand(time(NULL));
Look at the logic here:
for(i = 0; i < random; i++){
while(ch != '\n'){
ch = fgetc(src);
}
}
Once you hit a newline, you won't read any more characters, so you're always going to print either the first or second line.
You can fix it like this:
for(i = 0; i < random; i++){
ch = fgetc(src); // start by reading the first character on the line
while(ch != '\n'){
ch = fgetc(src);
}
}
Jim Balter also notes that ch would best be declared as an int. This is because EOF is not considered to be a regular character.
without printf("%c","\n"); line at the end it is working fine...

Resources