Spliting a string - c

I'm trying to make a program that should split a string in half but so far the program is printing out random letters when I want it to read what the user writes and use the string to split it in half. Another thing is that I'm not sure of is how to write the splitting into two (I have written that part as str/2).
int main() {
int x;
printf("Pick the program that should be executed:\n");
printf(" 1. Split text\n Enter an option:\n");
scanf("%d", &x);
if (x == 1) {
// testing example
printf("Write the text you want to use:\n");
char str[100];
fgets(str, 100, stdin);
printf("Input was: %s\n", str);
char test[] = str;
char *left;
char *right;
// first make a copy
left = strcpy(test);
// second locate the desired text and split in half
right = strstr(left, (str/2));
// third split the string
*(right - 1) = '\0';
// print the results
printf("Original : %s\nLeft side: %s\nRight side: %s\n\n", test, left, right);
// clean up
free(left);
}
return main();
}

This is a possible solution for your problem, and the problem was at Point 1 where either you use case A or case B. The problem here is that you were using both scanf and fgets functions and since scanf doesn't consume the \n and fgets does you would always get an "empty" string (just a \n) in the str variable. So in case A you just use another scanf or in case B you need to consume that last \n and then read the string you want.
Besides that, for the spliting part I'm just using a simple memcpy function and spliting the string in half with the help of strlen to calculate the string's length.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int x;
printf("Pick the program that should be executed:\n");
printf(" 1. Split text\n Enter an option:\n");
scanf("%d", &x);
if (x == 1) {
printf("Write the text you want to use:\n");
char str[100];
// -- Point 1 --
// A
//scanf("%s", str);
// B
getchar();
fgets(str, 100, stdin);
// -------------
printf("Input was: %s\n", str);
int len = strlen(str);
char *left, *right;
left = malloc(len/2 + 1);
right = malloc(len/2 + 1);
memcpy(left, str, len/2);
left[len/2] = 0;
memcpy(right, str + len/2, len/2);
right[len/2] = 0;
// print the results
printf("Original : %s\nLeft side: %s\nRight side: %s\n\n", str, left, right);
// clean up
free(left);
free(right);
}
return 0;
}

Related

How to parse through a string of STDIN word by word in C

I would like to read standard input of a command and its argument in a C program, for instance:
ATTACK 50 30
I would like my program to parse through the input using whitespace and assign each word to a variable but right now I would just like to print each word. However, when I tried the program only returned ATTACK and not ATTACK 50 30.
I tried:
int main(){
// Grid size declaration //
int *x, *y;
char command[20];
char user_input[100];
scanf("%s", user_input);
printf("%s", user_input);
return 0;
}
As I said I used ATTACK 50 30 as my STDIN but my printf function only returned ATTACK. I thought of maybe using a while loop to keep scanning until the character interpreted is the return key (which I believe in this case would just be the null character?). I tried it using the code below:
int main(){
// Grid size declaration //
int *x, *y;
char command[20];
char user_input[100];
while(scanf("%s", user_input)!="\0"){
scanf("%s", user_input);
printf("%s", user_input);
}
return 0;
}
This did not work, the error produced declared I was comparing a pointer to an integer.
Since you are dealing with stdin it would probably be a better idea to utilize the fgets function in lieu of the scanf function, and then parse the inputted line of data utilizing the strtok string function.
Utilizing that strategy, following is a snippet of code allowing for the parsing of entered text where each word or data group is identified.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 64
int main()
{
char line[MAX + 1];
const char delim[2] = " ";
char * wd;
printf("Enter some text or type \"quit\" to end: ");
while (fgets(line, MAX, stdin))
{
line[strlen(line) - 1] = ' '; /* Replace newline character at the end with a space */
wd = strtok(line, delim);
while (wd != NULL)
{
if (strcmp(wd, "quit") == 0)
{
return 0;
}
printf("%s\n", wd);
wd = strtok(NULL, delim);
}
printf("Enter some text or type \"quit\" to end: ");
}
return 0;
}
Testing out this code utilizing your text example yielded the following terminal output.
#Dev:~/C_Programs/Console/ParseWord/bin/Release$ ./ParseWord
Enter some text or type "quit" to end: ATTACK 50 30
ATTACK
50
30
Enter some text or type "quit" to end: quit
#Dev:~/C_Programs/Console/ParseWord/bin/Release$
This is just a springboard from where you might go, but test that out and see if it meets the spirit of your project.

How can I stop the input when I enter end

got this little problem, I made this code for my task, it should input strings and print it in revese, the loop should end when you enter end, but it doesnt end, I know this is not how you check strings but I don't know how to correct it. Thanks in advance for help.
#include <stdio.h>
#include <stdlib.h>
void reverse(char str[]){
int length;
for(length=strlen(str)-1; length >= 0; length--){
printf("%c",str[length]);
}
}
int main(void){
char str[]="";
while(str != "end"){
printf("\nEnter string: ");
scanf("%s", str);
reverse(str);
}
return 0;
}
you have many problems in your code :
when you write char str[]=""; this is will create a string of size = 1 only which will not accept any string you enter except for only one char , so you should do char str[50]; where 50 is the max expected length of the entered string.
it's not while(str != "end") it's , while(strcmp(str,"end") != 0) as you want to compare the strings itself not addresses
it's better to write scanf("%49s", str); than scanf("%s", str); just to make sure that the entered string will always fit in your array
in this line length = strlen(str)-1; , the strlen function return unsigned long long , so you should typecast that and write length = (int)strlen(str)-1; instead
with this all being said , this is the edited code :
#include <stdio.h>
#include <string.h>
void reverse(char str[]){
int length;
for(length = (int)strlen(str)-1; length >= 0; length--){
printf("%c",str[length]);
}
}
int main(void){
char str[50];
while(strcmp(str,"end") != 0){
printf("\nEnter string: ");
scanf("%49s", str);
reverse(str);
}
return 0;
}
and this is the output:
Enter string:abcd
dcba
Enter string:end
dne
Process finished with exit code 0

How to show the result of written strings

I'm learning C Programming and I can't resolve this issue.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
printf("Write Down Your First Name!\n\n");
scanf("%s", &first);
int last;
printf("\nNow Write Your Sir Name!\n\n");
scanf("%s", &last);
printf("\nYour Full Name is %s\n\n");
system("pause");
return 0;
}
And I want to show the full name written.
Should I use void?
Thanks in advance
first and last should be of char array type instead of int type if you want to store characters into that.
int first; ---> char first[100]; /* define how many char you want in first*/
similarly
int last; --> char last[100];
And while scanning it you don't have to pass &
scanf("%s", first);
scanf("%s", last);
Want to print/show ?
printf("\nNow Write Your Sir Name! %s n\n", first);/* you missed to pass argument to printf */
printf("\nYour Full Name is %s\n\n",first);
How to join both ? Iterate last upto '\0' char and copy each char of last to end of first
int len = strlen(first);
first[len] = ' ';/* if needed, put space at the end of first */
for( i = 0, j = len + 1 ; last[i]!='\0;i++,j++) {
first[j] = last[i]; /* first should have enough space */
}
first[j] = '\0';
Now print it as
printf("\nYour Full Name is %s\n\n",first);

Removing a character from string in C with a dynamic string

So, I want to create a function which creates and returns a dynamic string based on a string s without characters c. Now, I want to be able to remove all of the desired characters, no matter the case. Additionally, the original string entered by the user should remain unchanged. Here's my attempt, it keeps telling me about an error at line 12 (noted in the comments).
One more thing: I'm not sure if I wrote the remove function well, I think it should work? All of the pointers confused me a little bit.
#include <stdio.h>
#include <stdlib.h>
char * remove(char *s, char c);
int strlen(char *s);
int main() {
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf("%c", &c);
n = remove(s, c); // Place the new string in n so I wouldn't change s (the error)
printf("The new string is %s", n);
return 0;
}
int strlen(char *s)
{
int d;
for (d = 0; s[d]; d++);
return d;
}
char * remove(char *s, char c) {
char str[16], c1;
int i;
int d = strlen(s);
str = (char)calloc(d*sizeof(char)+1);
// copying s into str so I wouldn't change s, the function returns str
for (i = 0; i < d; i++) {
while(*s++ = str++);
}
// if a char in the user's string is different than c, place it into str
for (i = 0; i < d; i++) {
if (*(s+i) != c) {
c1 = *(s+i);
str[i] = c1;
}
}
return str; // the function returns a new string str without the char c
}
You declared n as 16-element array of char type:
char n[16];
So you cannot do:
n = remove(s, c);
because n is a const pointer.
Also your remove function returns a pointer to its local array, which gets destroyed as soon as your function returns. Better declare remove as
void remove(char *to, char *from, char var);
and pass n as the first parameter.
There ware so many mistakes in your program it was easier to rewrite and show you, with added comments. Note that scanf("%s... will accept only a single word, not a sentence (it stops at the first whitespace). And note that the newline will be left in the input buffer for scanf("%c... to read unless you add a space, as advised.
#include <stdio.h>
void c_remove(char *n, char *s, char c) { // renamed because remove() is predefined
while (*s) { // no need for strlen()
if (*s != c) // test if char is to be removed
*n++ = *s; // copy if not
s++; // advance source pointer
}
*n = '\0'; // terminate new string
}
int main(void) { // correct signature
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf(" %c", &c); // the space before %c cleans off whitespace
c_remove(n, s, c); // pass target string pointer too
printf("The new string is %s", n);
return 0;
}
Program sessions:
Please enter string: onetwothree
Which character do you want to remove? e
The new string is ontwothr
Please enter string: onetwothree
Which character do you want to remove? o
The new string is netwthree

How do I get rid of this new line?

I created a program that asks the user to input their name, and then manipulates it in multiple ways. The final way that it manipulates it is by printing the users name backwards. For instance if the user entered John Doe, the program would print Doe John. The only problem I'm having at this point is stopping my program from putting an unnecessary new line between the last and first name.
Example:
I want Doe John on one line but I get
Doe
John
For my assignment I need to get rid of this extra line. How do I do this?
#include <stdio.h>
#include <string.h>
void removeNewLine (char * userName, int charLenght)
{
int i=0;
do {
if (userName [i]=='\n')
{
userName [i]='\0';
}
i++;
} while (i<charLenght);
}
// This is going to tell me exactly how many real character are in my array
int myCounter (char * userName, int size)
{
int counter=0;
do
{
if(userName [counter]=='\0')
{
return counter; //I always thought that you needed to put your return at the end of the function, this is good to know that you don't need too
}
counter++;
}while (counter<size);
return -1;
}
int main ()
{
printf("Enter your first and last name\n");
char name [250]={'\0'};
char * space;
char *first=NULL, *last = NULL, *firstspace;
char *userName;
int numOfChars=0;
//Prevents the potential problem of an overflow = (sizeof(name)-1)
fgets(name,(sizeof(name)-1),stdin);
//This is what is actually doing the dirty work of removing the extra chars
removeNewLine(userName, numOfChars);
//This is going to count the number of characters that were input by the user
numOfChars = strlen(name)-1;
printf("You Entered: %s \n", name);
printf("There are %zu characters in your name including the space. \n", strlen(name));
char end;
int i;
end = strlen(name) -1;
printf("Your name backwards is");
for (i = end; i >= 0; --i)
{
printf("%c", name [i]);
}
printf("\nLooking for the space in your name \n", name);
firstspace=space=strchr(name, ' ');
*firstspace='\0';
while (space!=NULL)
{
printf("The space was found at character %d\n", space-name+1);
last = space+1;
space=strchr(space+1, ' ');
}
printf("%s%s", last, name);
*firstspace=' ';
//This is just to tell the user how many "real" characters were in there name
printf("\n There are %d actual characters in your name including the space", numOfChars);
}
Do little modification and Interchange these below two lines
removeNewLine(userName, numOfChars);
//This is going to count the number of characters that were input by the user
numOfChars = strlen(name)-1;
Like this
numOfChars = strlen(name); // first find the length of input.
removeNewLine(name, numOfChars); // And now remove newline at the end of input
EDIT
Your CODE
#include <stdio.h>
#include <string.h>
void removeNewLine (char * userName, int charLenght)
{
int i=0;
do {
if (userName [i]=='\n')
{
userName [i]='\0';
}
i++;
} while (i<charLenght);
}
int main ()
{
printf("Enter your first and last name\n");
char name [250]={'\0'};
char * space;
char *first=NULL, *last = NULL, *firstspace;
int numOfChars=0;
//Prevents the potential problem of an overflow = (sizeof(name)-1)
fgets(name,(sizeof(name)-1),stdin);
//This is what is actually doing the dirty work of removing the extra chars
numOfChars = strlen(name); // first find the length of input.
removeNewLine(name, numOfChars); // And now remove newline at the end of input
printf("You Entered: %s \n", name);
printf("There are %zu characters in your name including the space. \n", strlen(name));
char end;
int i;
end = strlen(name) -1;
printf("Your name backwards is");
for (i = end; i >= 0; --i)
{
printf("%c", name [i]);
}
printf("\nLooking for the space in your name \n", name);
firstspace=space=strchr(name, ' ');
*firstspace='\0';
while (space!=NULL)
{
printf("The space was found at character %ld\n", space-name+1);
last = space+1;
space=strchr(space+1, ' ');
}
printf("%s %s", last, name);
*firstspace=' ';
//This is just to tell the user how many "real" characters were in there name
printf("\n There are %d actual characters in your name including the space", numOfChars);
}
Output
Enter your first and last name
John Doe
You Entered: John Doe
There are 8 characters in your name including the space.
Your name backwards iseoD nhoJ
Looking for the space in your name
The space was found at character 5
Doe John
There are 9 actual characters in your name including the space
The best way is to use fgets() with a couple of helper functions:
/*Removes remaining characters from keyboard input buffer until next newline*/
/*Returns 0 if OK, a negative value if EOF.*/
int fpurge(FILE *f)
{
int c;
while((c=fgetc(f))!=EOF && c!='\n')
{ }
return (c==EOF ? -1 : 0);
}
/*Find and remove newline from string*/
/* Returns a nonzero value if found, zero if not. */
int truncate_newline(char *str)
{
int bRet=0;
if(str!=NULL)
{
char *pNewline = strchr(str, '\n');
if(pNewLine!=NULL)
{
bRet = 1;
*pNewLine = '\0';
}
}
return bRet;
}
/*Remove newline from string or excess characters from input buffer,
where appropriate.*/
/* Returns 0 if buffer is full, a positive value if line is complete,
a negative value if EOF (implies buffer full). */
int fclean(char *str, FILE *f)
{
int ret = 1;
if(!truncate_newline(str))
ret = fpurge(f);
return ret;
}
It's used this way:
char buf[42];
fgets(buf, sizeof buf, stdin);
fclean(buf);
Now you have a NULL-terminated, newlineless buf, and nothing in the input buffer to corrupt your next fgets call.
Like to offer an "after accepted" solution.
void *removeNewLineAfter_fgets(char *s) {
if (s) {
size_t l = strlen(s);
if ((l > 0) && (s[l-1] == '\n')) {
s[l-1] = '\0';
}
}
return s;
}
// Usage:
if (removeNewLineAfter_fgets(fgets(name,sizeof(name),stdin)) == NULL) { handle EOF }
BTW: OP does not need -1 in fgets(name,(sizeof(name)-1),stdin).

Resources