problem about replacing strings with specific characters - c-strings

I should write a function which is going to replace \n with \n and if it finds \n it should go to a newline in the string.
The problem is that the code returns the correct answer for the 2nd condition but false answer for the your text1st one.
Can someone explain what's wrong with the code,please?
void REPLACE(char *inputstring){
int strsize=strlen(inputstring);
int i=0;
int controller=0;
char *newstr=(char *)malloc(1024*sizeof(char));
while(i<strsize ){
if((strstr(&inputstring[i],"\\")==&inputstring[i]) && (strstr(&inputstring[i+1],"\\")==&inputstring[i+1]) && (strstr(&inputstring[i+2],"n")==&inputstring[i+2])){
strcpy(&newstr[i],&inputstring[i]);
strcpy(&newstr[i+1],&inputstring[i+2]);
controller=1;
i=i+3;
}
else if((strstr(&inputstring[i],"\\")==&inputstring[i]) && (strstr(&inputstring[i+1],"n")==&inputstring[i+1]) && controller==0){
strcpy(&newstr[i],"\r\n");
i=i+2;
controller=0;
}
else{
strcpy(&newstr[i],&inputstring[i]);
i++;
}
}
puts(newstr);
}
input: hi\nbye
expected output:hi\nbye
code's output:hi\nbbye

Related

What is going wrong when using getchar for my C program?

Hello folks it's my first question here :)
I just started studying CS in Berlin and tried to write a prog on my own which prints every charakter of a string literally in the terminal. And it works fine when defining the word which has to be printed in the C-Code.
int main () {
printf("Type in a word:\n");
char wort[] = "raffiniert";
int i = 0;
if (wort[i] == i)
{
printf("No word typed in!\n");
return 0;
}
while (wort[i] != '\0')
{
printf("%c \n", wort[i]);
i++;
}
return 0;
}
But when trying to implement getchar, so u can type in the console, not in the code, it fails. Regardless of how much other things I tried.
#include "stdio.h"
#include "stdlib.h"
int main ()
{
printf("Type in a word:\n");
int i = 0;
char wort;
wort = getchar();
if ((wort = getchar()) == i)
{
printf("No word typed in!\n");
return 0;
}
while ((wort = getchar()) != '\0')
{
printf("%c \n", wort);
}
return 0;
}
My problems are:
The program does not terminate automatically after printing out.
The first time typing in a word, it's printed uncompletely. It starts to print completely after the first time.
Could y'all at least give me advices what to correct?
Thanks and stay in good health.
"The program does not terminate automatically after printing out."
That's because your loop condition is incorrect. You want to check if getchar() returns EOF.
"The first time typing in a word, it's printed uncompletely. It starts to print completely after the first time."
That is because you are discarding the first two characters of input. You have 2 calls to getchar() where you basically discard the result. Just do:
#include <stdio.h>
int main (void)
{
int wort; /* Must be int to compare with EOF */
int i = 0;
while( (wort = getchar()) != EOF ){
putchar(wort);
i += 1;
}
if( i == 0 ){
fprintf(stderr, "No word typed in!\n");
return 1;
}
return 0;
}

scanf() method does not working in while loop?

I've been out of this loop for 5 hours. My scanf method does not work.
Here is my loop.
I could not execute library's strcmp so I wrote myself.
int string_compare(char str1[], char str2[])//Compare method
{
int ctr=strlen(str1);
int ctr2=strlen(str2);
int counter=0;
if(strlen(str1)!=strlen(str2) ){//if their lengths not equal -1
return -1;
} else
{
for (int i = 0; i < strlen(str1); ++i)
{
if(str1[i]==str2[i]){ //looking for their chars
counter++;
}
}
if(counter==strlen(str1)){
return 0;
} else
{
return -1;
}
}
}
char str1[100]; //for users command
char newString[10][10]; //after spliting command i have
while(string_compare(newString[0],"QUIT") != 0){
printf("Enter Commands For Execution\n");
scanf("%10[0-9a-zA-Z ]s\n",str1);
int i,j,ctr;
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
} else
{
newString[ctr][j]=str1[i];
j++;
}
}
if(string_compare(newString[0],"QUIT") == 0){
printf("Quitting\n");
break;
}
if(string_compare(newString[0],"MRCT") == 0){
printf("hey\n");
}
if(string_compare(newString[0],"DISP") == 0){
printf("hey2\n");
}
}
When I execute my c file,
the loop asks me to enter command such as "MRCT".
It forever prints
Enter Command
hey
Enter Command
hey
My way of using scanf() does not work here.
The scanf() stops scanning after the first failure.
So here:
scanf("%10[0-9a-zA-Z ]s\n",str1);
The scan tries to interpret three things:
A string %[] into a variable str1
the character s
The character '\n' which will result in a sequence of white space characters being read from the input.
Note if the string is zero length it will fail at the string and not interpret the s or the \n character.
One: I suspect that s is an error and you don't want it.
Two: Don't use "%[^\n]\n" to read a line. As this fails if the line is empty (just has the \n character).
if (scanf("%10[0-9a-zA-Z ]", str1) == 1)
{
// Always check that the value was read.
// Then deal with it.
....
}
scanf("%*[^\n]"); // Ignore any remaining character above 10.
// Note this may still fail so don't add \n on the end
// Deal with end of line separately.
char c;
if (scanf("%c", &c) == 1 && c == '\n') // Now read the end of line character.
{
// End of line correctly read.
}
Use: scanf("%[^\n]\n" , str1); to get a line using scanf function.

print each letter after '.' for example if I enter a..bcde..fg..h the program will print bfh

I'm new to C, I have been asked to make a program in C asking to print each letter after a '.' after a user has entered an input.
For example if the user enters a..bcd..e.f..gh the output should be befg
which is the exact example I have been given in class.
I assume this would need to use pointers but I am unsure how to deal with this question, here is what I have tried to do so far. I know it is not correct, please help me understand how to use pointers to deal with this question.
#include <stdio.h>
int main() {
char *c, count =0;
printf("enter some characters");
scanf("%s", &c);
while( c != EOF ) {
if (c != '.') {
count ++;
}
else; {
printf("%s", c);
}
}
}
The program can look the following way
#include <stdio.h>
#define N 100
int main( void )
{
char s[N];
const char DOT = '.';
printf( "Enter some characters: " );
fgets( s, N, stdin );
for ( char *p = s; *p; ++p )
{
if ( p[0] == DOT && p[1] != DOT ) putchar( p[1] );
}
putchar( '\n' );
}
Its output might look like
Enter some characters: a..bcd..e.f..gh
befg
Take into account that here any symbol after a dot (except the dot itself) is printed. You can add a check that there is a letter after a dot.
You don't really need pointers for this, or even an array. Basically it's a simple state engine: read each character, if '.' is encountered, set a flag so the next character is printed.
#include <stdio.h>
int main() {
int c, flag = 0;
while ((c = getchar()) != EOF) {
if (c == '.')
flag = 1;
else if (flag) {
putchar(c);
flag = 0;
}
}
return 0;
}
There are some errors in your code:
- char* c means a pointer to one or more characters.
But where does it point to?
- scanf reads a string up to an "white space". White space characters are the space itself, a newline, a tab character or an EOF. scanf expects a format string and a pointer to a place in memory where it places what it reads. In your case c points to an undefined place and will overwrite whatever there is in memory.
- why do you place a ";" after the else? The else clause will end with the ";". So your program will do the print every time.
It helps you a lot if you format your code in a more readable way and give the variable names that give hint what they are used for.
Another very important thing is to initialize every variable that you declare. Errors with uninitialized variables are sometimes very hard to find.
I would do it this way:
#include <stdio.h>
int main(int argc, char* argv[])
{
// I read every single character. The getchar function returns an int!
int c = 0;
// This marks the program state whether we must print the next character or not
bool printNext = false;
printf("enter some characters");
// We read characters until the buffer is empty (EOF is an integer -1)
do
{
// Read a single character
c = getchar();
if ( c == '.')
{
// After a point we change our state flag, so we know we have to print the next character
printNext = true;
}
else if( c != EOF )
{
// When the character is neither a point nor the EOF we check the state
if( printNext )
{
// print the character
printf( "%c", c );
// reset the state flag
printNext = false;
}
}
// read until the EOF occurs.
}
while( c != EOF );
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char letter;
char *c;
c = malloc(256);
printf("enter the string : ");
scanf("%s", c);
while( (letter=*(c)) != '\0' )
{
if (letter == '.')
{
c++;
letter=*c;
if(letter!='.')
printf("%c",letter);
else
{
while(letter=='.')
{
c++;
letter=*c;
}
printf("%c",letter);
}
}
c++;
}
printf("\n");
}

Reading a whole line before printing result

Ok firstly I'm a total amateur on programming and i wanted to try something. I want to make a C program which will read a line and then if the characters are accepted to print "ACCEPTED" or "REJECTED" if the characters are valid or not.
So I've used a while loop and some if-else if to add the viable characters. The viable characters are the letters of the alphabet ',' '.' '/' '[' ']'. The problem is that after i type the whole line, it prints ACCEPTED and REJECTED for every character on the line. How can i get the program to read the whole line first and then print the result?
#include <stdio.h>
int main(void) {
char c;
c=getchar();
while(c!=EOF) {
while (c!='\n') {
if (c>='a' && c<='z') {
printf("OK!\n");
}
else if(c==','|| c=='.' ||c=='/') {
printf("OK!\n");
}
else if(c==']'||c=='[') {
printf("OK!\n");
}
else {
printf("ERROR!\n");
}
c=getchar();
}
c=getchar();
}
}
Sorry, my original answer did not seem to relate to your question. Skim reading fail.
Thank you for posting the code, it helps a lot when it comes to answering your question correctly.
Ignoring style for now, I would change your code in this way to make it print OK only when you finish parsing the entire line and it is exactly what #ScottMermelstein said but with code.
#include <stdio.h>
int main(void) {
int c; // This needs to be an int otherwise you won't recognize EOF correctly
int is_ok;
c=getchar();
while(c!=EOF) {
is_ok = 1; // Let's assume all characters will be correct for each line.
while (c!='\n') { // So long as we are in this loop we are on a single line
if (c>='a' && c<='z') {
// Do nothing (leave for clarity for now)
}
else if(c==','|| c=='.' ||c=='/') {
// Do nothing (leave for clarity for now)
}
else if(c==']'||c=='[') {
// Do nothing (leave for clarity for now)
}
else {
is_ok = 0; // Set is_ok to false and get out of the loop
break;
}
c=getchar();
}
if (is_ok) // Only print our result after we finished processing the line.
{
printf("OK!\n");
} else
{
printf("ERROR!\n");
}
c=getchar();
}
return 0; // If you declare main to return int, you should return an int...
}
However, I would recommend modularizing your code a little more. This will come with time and practice but you can write things in a way that is much easier to understand if you hide things away in appropriately named functions.
#include <stdio.h>
int is_valid_char(int c)
{
return (isalpha(c) || c == ',' || c == '.' || c == '/' || c == '[' || c == ']');
}
int main(void) {
int c;
int is_valid_line;
c=getchar();
while(c!=EOF) {
is_valid_line = 1;
while (c!='\n') {
if (!is_valid_char(c)) {
is_valid_line = 0; // Set is_valid_line to false on first invalid char
break; // and get out of the loop
}
c=getchar();
}
if (is_valid_line) // Only print our result after we finished processing the line.
{
printf("OK!\n");
} else
{
printf("ERROR!\n");
}
c=getchar();
}
return 0;
}
You can use scanf and putting a space before the format specifier %c to ignore white-space.
char ch;
scanf(" %c", &ch);
This might be what you are looking for?
Read a line and process good/bad chars and print either OK or Error.
#include <stdio.h>
int main ( void )
{
char buff[1000];
char *p = buff ;
char c ;
int flgError= 0 ; // Assume no errors
gets( buff ) ;
printf("You entered '%s'\n", buff );
while ( *p ) // use pointer to scan through each char of line entered
{
c=*p++ ; // get char and point to next one
if ( // Your OK conditions
(c>='a' && c<='z')
|| (c>='A' && c<='Z') // probably want upper case letter to be OK
|| (c==','|| c=='.' ||c=='/')
|| (c==']'||c=='[')
|| (c=='\n' ) // assume linefeed OK
)
{
// nothing to do since these are OK
}
else
{
printf ("bad char=%c\n",c);
flgError = 1; // 1 or more bad chars
}
}
if ( flgError )
printf ( "Error\n" );
else
printf ( "OK\n" );
}

Removing Characters of a String

I'm trying to write a code that asks the user to enter a string and takes of all characters except the alphabetical.
Now i did it myself and it doesn't seem to work properly. I'm new to strings so i'm trying to understand and master strings. I tried to use gdb on mac but i don't have all the functions to understand this.
Could you please help?
What the code must do: User inputs (for example): h**#el(l)o&^w
and the output is hello.
here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int i;
int seen = 0;
printf("Enter String: ");
scanf("%s", string);
for (i=0; string[i]!='\0'; i++)
{
if (((string[i]<='a' || string[i]>'z')&&(string[i]<='A' || string[i]>'Z')) ||string[i]!='\0')
{
seen = 1;
}
else
seen = 0;
}
if (seen==0)
{
printf("%s", string);
}
}
well, your code has a couple of important problems:
you're not checking boundaries when iterating… what if I type in a 101 characters string? and a 4242 characters string?
next problem, is that scanf("%s", …) is considered dangerous, for the same reasons
so basically, what you'd want is to use fgets() instead of scanf().
But why not just get the input character by character, and build a string that has only the chars you want? It's simpler and flexible!
basically:
#include <ctype.h>
int main() {
char* string[100];
int i=0;
printf("Enter your string: ");
do {
// getting a character
char c = getchar();
// if the character is alpha
if (isalpha(c) != 0)
// we place the character to the current position and then increment the index
string[i++] = c;
// otherwise if c is a carriage return
else if (c == '\r') {
c = getchar(); // get rid of \n
// we end the string
string[i] = '\0'
}else if (c == '\n')
// we end the string
string[i] = '\0';
// while c is not a carriage return or i is not out of boundaries
} while (c != '\n' || i < 100);
// if we've got to the boundary, replace last character with end of string
if (i == 100)
string[i] = '\0';
// print out!
printf("Here's your stripped string: %s\n", string);
return 0;
}
I did not run it on my computer because it's getting late, so my apologies in case of mistakes.
Addendum:
wee the program skips my statement and shuts down
that's because your condition is inversed, and remove the \0 condition, as it will always happen with the scanf() that always append \0 to the string to end it. Try exchanging seen = 1 and seen = 0 or try using the following condition:
if ((string[i]>='a' && string[i]<='z')||(string[i]>='A' && string[i]<='Z')))
seen = 1;
else
seen = 0;
or simply, use ctypes's isalpha() function, like in our two examples!
No part(remove the extra characters) to change the string in your code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *filter(char *string, int (*test)(int)) {
char *from, *to;
for(to = from = string;*from;++from){
if(test(*from))
*to++ = *from;
}
*to = '\0';
return string;
}
int main(){
char string[100];
printf("Enter String: ");
scanf("%99s", string);
printf("%s\n", filter(string, isalpha));
return 0;
}

Resources