skip whitespaces but not newline in c without break and continue - c

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);
}

Related

Removing a newline from the middle of a string using getchar

Right now I have a string looking like this:
A sentence
with a newline.
I'm reading the string in via console input like so:
ch = getchar();
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
}
And, after reading it in, I remove the whitespace present by doing this in a function and applying to the msg char array:
char *remove_white_spaces(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
I've tried looping over it and stopping at \n but that leaves an output of "Asentence", as the string terminates as the \n is set to 0.
Whole main:
int main(void) {
char msg[MAX_MSG_LEN+1];
char ch;
int i = 0;
ch = getchar();
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
}
msg[i] = '.';
msg[i + 1] = '\0';
remove_white_spaces(msg);
printf("%s\n", msg);
return 0;
}
You can use the isspace function to test for and skip any/all whitespace characters, include the normal space and the newline character(s):
#include <ctype.h> // For definition of "isspace"
char *remove_white_spaces(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (!isspace((unsigned char)(str[i])))
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
On the reason for casting the argument to isspace to an unsigned char, see this discussion.
Function removing and replacing any chars in the string.
toRemove - chars to remove
addSpace - replace with space
allowMultiple - allow multiple spaces when replacing more adjanced
characters
allowEdges - allow adding spaces at the from and at the end
char *removeChars(char *str, const char *toRemove, const int addSpace, const int allowMultiple, int const allowEdges)
{
char *rd = str, *wr = str;
int replaced = 0;
if(rd)
{
while(*rd)
{
if(strchr(toRemove, *rd))
{
if(addSpace)
{
if(!replaced || allowMultiple)
{
if(wr != str || (wr == str && allowEdges))
{
*wr++ = ' ';
replaced = 1;
}
}
}
}
else
{
*wr++ = *rd;
replaced = 0;
}
rd++;
}
if(allowEdges) *wr = 0;
else
while((wr - 1) > str)
{
if(*(wr - 1) == ' ') {*(wr - 1) = 0; wr--;}
else break;
}
}
return str;
}
int main(void)
{
char str[] = "%%%%%A sentence\n\n\nwith!##$%^a newline.%%%%%%%";
printf("`%s`\n", removeChars(str,"\n!##$%^", 1, 0, 0));
}
Following the suggestion of #MarkBenningfield I did the following and checked for '\n' and just replaced it with a space.
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
if (ch == '\n') {
ch = ' ';
}
}

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;
}

My program is not accepting simple string in c using getchar

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
*/

C language: change user input

I need to write program that get Input from user and in case i have quate (") i need to change all the chars inside the quotes to uppercase.
int main()
{
int quoteflag = 0;
int ch = 0;
int i = 0;
char str[127] = { '\0' };
while ((ch = getchar()) != EOF && !isdigit(ch))
{
++i;
if (ch == '"')
quoteflag = !quoteflag;
if (quoteflag == 0)
str[i] = tolower(ch);
else
{
strncat(str, &ch, 1);
while ((ch = getchar()) != '\"')
{
char c = toupper(ch);
strncat(str, &c, 1);
}
strncat(str, &ch, 1);
quoteflag = !quoteflag;
}
if (ch == '.')
{
strncat(str, &ch, 1);
addnewline(str);
addnewline(str);
}
else
{
if ((isupper(ch) && !quoteflag))
{
char c = tolower(ch);
strncat(str, &c, 1);
}
}
}
printf("\n-----------------------------");
printf("\nYour output:\n%s", str);
getchar();
return 1;
}
void addnewline(char *c)
{
char tmp[1] = { '\n' };
strncat(c, tmp, 1);
}
So my problem here is in case my input is "a" this print at the end "A instead of "A" and i dont know why
The problem is that you are using strncat in a weird way. First, strncat will always do nothing on big-endian systems. What strncat does is read the inputs ... as strings. So passing and int (four or eight bytes) into the function, it'll read the first byte. If the first byte is 0, then it'll believe it is the end of the string and will not add anything to str. On little endian systems, the first byte should be the char you want, but on big-endian systems it will be the upper byte (which for an int that holds a value less than 255, will always be zero). You can read more about endianness here.
I don't know why you're using strncat for appending a single character, though. You have the right idea with str[i] = tolower(ch). I changed int ch to char ch and then went through and replaced strncat(...) with str[i++] = ... in your code, and it compiled fine and returned the "A" output you wanted. The source code for that is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int quoteflag = 0;
char ch = 0;
int i = 0;
char str[127] = { '\0' };
while ((ch = getchar()) != EOF && !isdigit(ch))
{
if (ch == '"')
quoteflag = !quoteflag;
if (quoteflag == 0)
str[i++] = tolower(ch);
else
{
str[i++] = ch;
while ((ch = getchar()) != '\"')
{
char c = toupper(ch);
str[i++] = c;
}
str[i++] = ch;
quoteflag = !quoteflag;
}
if (ch == '.')
{
str[i++] = '.';
str[i++] = '\n';
str[i++] = '\n';
}
else
{
if ((isupper(ch) && !quoteflag))
{
char c = tolower(ch);
str[i++] = c;
}
}
}
printf("\n-----------------------------");
printf("\nYour output:\n%s", str);
getchar();
return 1;
}
You should delete the ++i; line, then change:
str[i] = tolower(ch);
To:
str[i++] = tolower(ch);
Otherwise, since you pre-increment, if your first character is not a " but say a, your string will be \0a\0\0.... This leads us on to the next problem:
strncat(str, &ch, 1);
If the input is a", then strncat(str, &'"', 1); will give a result of \"\0\0... as strncat will see str as an empty string. Replace all occurrences with the above:
str[i++] = toupper(ch);
(The strncat() may also be technically undefined behaviour as you are passing in an malformed string, but that's one for the language lawyers)
This will keep track of the index, otherwise once out of the quote loop, your first str[i] = tolower(ch); will start overwriting everything in quotes.

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);

Resources