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;
}
Related
QUESTION:
What is wrong with this code example, what is missing?
Current incorrect output is:
There are 0 words in ""
Code Explanation:
Write a program that reads in a line of text, and prints out the number of words in that line of text. A word contains characters that are alphanumeric. Hint: Use the fgets() function.
Sample run:
Input:
from here to eternity
Output:
4
Input:
start here and turn 180 degrees
Output:
6
Code Snippet:
https://onlinegdb.com/H1rBwB83V
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#define MAXLEN 100
int countWords(char str[])
{
int i=0;
int count = 0;
bool flag = false;
while (str[i] != '\0')
{
if (isalnum(str[i]))
{
if (!flag)
{
count++;
flag = true;
}
}
else
flag = false;
i++;
}
return count;
}
int main(int argc, char **argv) {
char str[MAXLEN];
int count;
while (fgets(str, sizeof(str), stdin) != NULL)
{
str[strlen(str-1)] = '\0'; // the last character is the newline. replace with null
count = countWords(str);
printf("There are %d words in \"%s\"\n", count, str);
}
return 0;
}
Similar Tutorial:
https://www.sanfoundry.com/c-program-count-words-in-sentence/
You have an error here:
str[strlen (str - 1)] = '\0'; // the last character is the newline. replace with null
Using the pointer str - 1 leads to undefined behavior, as it points to memory outside the original string.
You actually meant to do this: strlen(str) - 1 (notice the -1 is moved outside the parentheses)
I'm stuck on trying to figure out how to make certain letters of a character string in an array that are input as all lower case and an underscore (i.e. "first_last") output with a space between them and each beginning letter being capitalized (i.e. "First Last").
Any helpful ideas are appreciated
Here's what I have so far:
#include <stdio.h>
#define SIZE 30
int main()
{
char string1(SIZE); //reserve a name of up to 29 characters
//read characters from input into array string 1
printf("%s", "Enter a name:);
scanf("%29s", string1);
}
You can just process a string character by character and modify the relevant characters, something like:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Capitalise based on your specs.
static void cap(char *str) {
// No actions for empty string.
if (*str == '\0') return;
// Always upper first character.
str[0] = toupper(str[0]);
// Check all but last character (ignore trailing '_').
for (size_t i = 1, count = strlen(str) - 1; i < count; ++i) {
// If underscore, make space and upper next character.
if (str[i] == '_') {
str[i] = ' ';
str[i+1] = toupper(str[i+1]);
}
}
}
// Test driver to do all arguments.
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; ++i) {
printf("'%s'", argv[i]);
cap(argv[i]);
printf("-> '%s'\n", argv[i]);
}
}
You'll probably want to handle edge cases but, since you haven't specified the desired behaviour for them, I've just left them as further exercises for the reader. Things to think about are:
how to handle string with multiple____underscores;
how to treat _ at end of string;
how to treat _ if not followed by a lower-case letter; and
quite possibly other things I haven't thought of :-)
Here's a sample run so you can see it in action:
pax$ testprog first_second one one_two
'first_second'-> 'First Second'
'one'-> 'One'
'one_two'-> 'One Two'
C isn't the language I know so I'm out of my comfort zone (learning C) and I have ran into an issue that I can't currently figure out.
I am trying to read from a text file one word at a time and compare it to a word that I have passed into the function as a pointer.
I am currently reading it from the file one character at a time and storing those characters in a new char array until it hits a space, then comparing that char array to the original word stored in the pointer (stored where it's pointing to, anyway).
When I do a printf to check if both arrays are the same they are, they both equal "Hello". At first I thought maybe it's because my char array doesn't have an end terminator but I tried adding one but still nothing is seeming to work.
My code is below and I would appreciate any help. Again C isn't my strong area.
If I do "Hello" it will be > 0 by the way, so I think it's because the gets() stdin function is also including the enter key or something of that sort. I am not sure of a better way to grab the string though.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int partA(char*);
main()
{
// Array to store my string
char myWord[81];
// myword = pointer to my char array to store. 80 = the size (maximum). stdin = standard input from my keyboard.
fgets(myWord, 80, stdin);
partA(myWord);
}
int partA(char *word)
{
// points to file.
FILE *readFile;
fopen_s(&readFile, "readThisFile.txt", "r");
char character;
char newWord[50];
int i = 0;
while ((character = fgetc(readFile)) != EOF)
{
if (character == ' ')
{
newWord[i] = '\0';
int sameWord = strcmp(word, newWord);
printf("Word: %s", word);
printf("newWord: %s", newWord);
if (sameWord == 0)
printf(" These words are the same.");
if (sameWord > 0)
printf(" sameWord > 0.");
if (sameWord < 0)
printf(" sameWord < 0.");
printf("\n");
i = 0;
}
if (character != ' ')
{
newWord[i] = character;
i++;
}
printf("%c", character);
}
fclose(readFile);
return 1;
}
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");
}
So I have been taking classes on C and one of the exercises was to program a caesar cipher program that both encrypts and decrypts. And when the input is "ab cd", the output should be "de#fg" but instead it outputs "de?g?". So my guess is the spacebar messes everything up. But also another error was found when I inputted "a" and it outputted "d?ad?". Thanks in advance.
#include <stdio.h>
#include <string.h>
void cipher(char plain_str[], char cipher_str[]);
void decipher(char cipher_str[], char decipher_str[]);
int main() {
char plain_str[30];
char cipher_str[30];
char decipher_str[30];
printf("Enter plain string: ");
scanf("%s", plain_str);
cipher(plain_str, cipher_str);
decipher(cipher_str, decipher_str);
}
void cipher(char plain_str[], char cipher_str[]) {
int i = 0;
while(plain_str[i] != '\0') {
if((plain_str[i]+3) >= 0 && (plain_str[i]+3) <= 127) {
cipher_str[i] = plain_str[i] + 3;
} else {
cipher_str[i] = plain_str[i] - 124;
}
i++;
}
printf("%s\n", cipher_str);
}
void decipher(char cipher_str[], char decipher_str[]) {
//asdf
}
The %s operator in scanf only reads a single word, not a whole line. So if you enter ab cd, only ab is put into plain_str. To read a whole line, use fgets():
fgets(plain_str, sizeof(plain_str), stdin);
size_t len = strlen(plain_str);
if (plain_str[len-1] == '\n') {
plain_str[len-1] = '\0'; // Remove newline
}
The other problem is that you're never adding the null terminator to cipher_str, so you're printing whatever garbage is in it after the encoded characters. The simplest way to resolve this is to initialize it to an all-zero array when you declare the variable:
char cipher_str[30] = {0};