Storing separated strings - c

So I'm trying to write this program that takes a string, seperates the strings into words and puts the seperated words into a format like "word1+word2+word3..."
I've written a C program that gets a string and seperates the string into words. But I'm a little confused on how to keep each individual word and then place it in the above format.
Here is my code so far
#include <stdio.h>
#include <string.h>
int main()
{
int wordCount = 0;
char realString[200];
char testString[200];
char * nextWordPtr;
printf("Input string\n");
gets(realString);
strcpy(testString,realString);
nextWordPtr = strtok(testString," "); // split using space as divider
while (nextWordPtr != NULL) {
printf("word%d %s\n",wordCount,nextWordPtr);
wordCount++;
nextWordPtr = strtok(NULL," ");
}
}
Does anyone have any suggestions?

I don't understand really what you want? if you just want to output the string like this : 'word0+word1+...etc', you can use this code to accomplish this:
#include <stdio.h>
#include <stdlib.h>
#define INPUT_STRING_LEN 128
int main(int argc, char **argv)
{
char input_string[INPUT_STRING_LEN];
char *out_string;
int index;
/* Get user input */
fgets(input_string, INPUT_STRING_LEN, stdin);
out_string = (char *) malloc((INPUT_STRING_LEN + 1) * sizeof(char));
/* Loop through input string and replace space with '+' */
index = 0;
while (input_string[index] != '\0')
{
if (input_string[index] == ' ')
out_string[index] = '+';
else
out_string[index] = input_string[index];
index++;
}
/* We got this out string */
fprintf(stdout, "We got this out string :\n--->\n%s<---\n", out_string);
/* Free the allocated memory */
free(out_string);
return 0;
}
If you want something else please edit the question.

Related

If i input too many characters my program either has a 'mremap_chunk(): invalid pointer' or a 'realloc(): invalid old size'

my program was built as a test to input as many sentences as the user want (until he enters -1), and then concatenate all sentences (\n included). If i input some characters is fine, but if i input more then 25 characters i have the two errors listed above, i tried simulating what would happen in paper and i canĀ“t find the problem, help is appreciated, thanks in advance.
The code is displayed below:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *s = malloc(1), *sentence = malloc(0);
int sSize = 0;
printf("Insert sentences, press '-1' if you want to exit:\n");
do
{
fgets(s,100,stdin);
if(strcmp(s,"-1\n") != 0)
{
sSize += strlen(s);
sentence = realloc(sentence, sSize * sizeof(char));
//s[strcspn(s, "\0")] = '\n';
strcat(sentence, s);
}
}while(strcmp(s,"-1\n") != 0);
printf("==================sentence================\n");
printf("%s", sentence);
return 0;
}
This is a classic buffer overrun problem:
s = malloc(1) - s now points to a one-character buffer.
fgets(s,100,stdin); - reads up to 100 characters into s - which is a one-character buffer.
EDIT
Here's a version which works and doesn't use a separate "sentence buffer":
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
const char *terminator = "-1\n";
char *sentences = malloc(100);
char *pNext_sentence;
printf("Insert sentences, press '-1' if you want to exit:\n");
*sentences = '\0';
do
{
sentences = realloc(sentences, strlen(sentences)+100);
pNext_sentence = sentences + strlen(sentences);
fgets(pNext_sentence, 100, stdin);
} while(strcmp(pNext_sentence, terminator) != 0);
*(sentences + (strlen(sentences) < strlen(terminator) ? 0 : strlen(sentences) - strlen(terminator))) = '\0';
printf("==================sentences================\n");
printf("%s", sentences);
free(sentences);
return 0;
}
You must use reallocate memory with realloc before using fgets, which, in your case, reads 100 bytes.
Your string has the initial size of 1.

Finding a reversed words in a given string using C program

Actually I have been searching for more than 1 week to find a solution for finding a reversed words in a given string using C. My question is, I have been given a string like this "bakelovekac". Here I have a reversed word of "ake" as "eka" in a string. Now I need to find out this reversed word in a given string and print it. How can it be done? Thanks in advance!
A basic approach would be to iterate over all the characters of the string and for each character check if it is being repeated, if yes then check for the presence of a possible reverse string.
A crude code for above approach would look something like this:
#include <stdio.h>
void checkForRevWord(char *str, char *rev){
int length = 0;
while(1){
if(str >= rev)
break;
if(*str != *rev)
break;
length++;
str++;
rev--;
}
if(length > 1){
while(length--)
printf("%c", *(rev+length+1));
printf("\n");
}
return;
}
int main()
{
char *inputStr = "bakelovekac";
char *cur = inputStr;
char *tmp;
while(*cur != '\0'){
tmp = cur+1;
/* find if current char gets repeated in the input string*/
while(*tmp != '\0'){
if(*tmp == *cur){
checkForRevWord(cur, tmp);
}
tmp++;
}
cur++;
}
}
Go through this program
#include <stdio.h>
#include <string.h>
int main()
{
char text[50]; //this character array to store string
int len,i;
printf("Enter a text\n");
scanf("%[^\n]s",text);//getting the user input with spaces until the end of the line
len=strlen(text);//getting the length of the array and assigning it the len variable
for(i=len-1;i>=0;i--)
{
printf("%c",text[i]); //printing the text from backwards
}
return 0;
}
thank you.

Reversing a string in C using Visual Studio

I'm building a program for reversing a string in visual studio, and while I run the code and enter a word I want to reverse, the program crashes.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(" %s", r, sizeof(r));
d = strlen(r);
for (i=d;i!=0;i--) {
printf("%s",i);
}
return 0;
}
Please note that I tried your program on Linux, so no MS Visual C++ and more specifically no conio.h and gets_s.
There are multiple problems with your program:
Your call to gets_s is incorrect, according to this and this, gets_s is defined as:
char *gets_s(
char *buffer,
size_t sizeInCharacters
);
You are calling it with illegal arguments. Instead of gets_s(" %s", r, sizeof(r)); you need to call it like this:
gets_s(r, 256);
the first parameter is pointer to the string buffer where the gets_s function will store the line from input and the second is the size of the buffer, note that in char r[256] you can store 255 characters and terminating zero (\0).
Your for loop is incorrect instead of for (i=d;i!=0;i--) { you need to do it like this:
for (i=d-1;i>=0;i--) {
now the loop starts from last character instead of \0 and ends when the i < 0 ie. the last print will be when i=0.
And your final mistake is that you are using printf incorrectly instead of printf("%s",i); you need to do:
printf("%c",r[i]);
because you are printing characters: "%c" is for char output and r[i] is i-th character from string r (don't forget that we count from 0).
So, in total this is how the program should look like:
#include <stdio.h>
#include <conio.h> // does not exist on GCC (Linux)
#include <string.h>
main(void) {
char r[256]; // 255 characters + \0
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, 256); // store at most 255 characters + \0
// does not work on GCC (Linux) even with -std=C11
d = strlen(r);
// start from last character and include first
for (i=d-1;i>=0;i--) {
// %c - character, r[i] gets the i-th character from string r
printf("%c",r[i]);
}
return 0;
}
void rev(char *s)
{
char *start, *end;
end = start + strlen(s) - 1;
for (start = s; end > start; ++start, --end) {
char tmp;
tmp = *start;
*start = *end;
*end = tmp;
}
}
Use the fgets function, and also put the reversing code in its own function, like I did. So the final code is
int main()
{
char line[80];
fgets(line, 80, stdin);
/* don't allow empty string */
if (*line == '\0') {
fprintf(stderr, "Empty string is not a string\n");
return 1;
}
/* remove the \n placed by fgets */
remnl(line);
rev(line);
printf("%s\n", line);
return 0;
}
void remnl(char *s) { s[strlen(s) - 1] = 0; }
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, sizeof(r));
d = strlen(r) - 1;
for (i = d; i >= 0; i--) {
printf("%c", r[i]);
}
_getch();
return 0;
}

Print words in string in reverse order C

I take user input using fgets() and store it into a temp array. I then concatenate that to a main array called userInput so that the user can enter multiple lines.
Let's say the user enters the following:
This is a sentence
This is a new line
I need it to print each line in the order they were entered but reverse the order of words like below:
sentence a is This
line new a is This
I have the current approach but I get this:
line
new a is sentence
This a is This
Below is my code where I call reversePrint() with a string to reverse:
void printToSpace(const char *str) {
do {
putc(*str, stdout);
} while(*str++ != ' ');
}
void reversePrint(const char *str) {
const char *p = strchr(str, ' ');
if (p == NULL) {
printf("%s", str);
}
else {
reversePrint(p + 1);
printToSpace(str);
}
}
Here is an alternative way:
#include <stdio.h>
#include <string.h>
void reversePrint(const char *str)
{
if (str)
{
reversePrint(strtok (NULL, " \t\n\r"));
printf("%s ", str);
}
}
int main(void)
{
char string[] = "This is a sentence";
reversePrint(strtok(string, " \t\n\r"));
return 0;
}
It seems so clear and simple that I suspect if strtok() is born for requirements like this.
Here are just a few thoughts...
I feel that using fgets will provide you with an undesired new-line marker. Hence, you need to handle the "\r\n" in the reverse printing function.
I feel that the reverse printing is easier to perform in a single function, although I loved the recursive approach, so I'll use it here.
I should point out that I wouldn't use a recursive function if this was a production application, as we'll be wasting resources and bloating the stack for no good reason.
On a non-recursive approach I would probably use the %.*s format, instead of printing each char separately.
I think your code would work if you only changed printToSpace so that it manages the \n contingency - but I felt like re-writinfg the function. Try this in your solution:
void printToSpace(const char *str) {
do {
putc(*str, stdout);
} while(*str && *str != '\n' && *str != '\r' && *str++ != ' ');
}
Here's my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_rev(char* str);
// collects two strings and send them to the `print_rev` function
int main(int argc, char const* argv[]) {
char str_array[2][255];
// Get string 1
printf("Enter the first string (up to 255 characters):\n");
fgets(str_array[0], 255, stdin);
printf("Please enter the second string (up to 255 characters):\n");
fgets(str_array[1], 255, stdin);
printf("You entered:\n1. %s2. %s", str_array[0], str_array[1]);
printf("\nString 1 reversed: ");
print_rev(str_array[0]);
printf("\nString 2 reversed: ");
print_rev(str_array[1]);
printf("\n");
}
// prints a string in reverse order.
void print_rev(char* str) {
// find the first occurrence of the ` ` (space)
char* p = strchr(str, ' ');
// if a space exists...
if (p) {
// call `print_rev` for whatever's after the space.
print_rev(p + 1);
// print a space
putc(' ', stdout);
}
// print every character until an EOL, space or NULL is encountered
while (*str && *str != ' ' && *str != '\n' && *str != '\r')
putc(*(str++), stdout);
}
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100000
int main()
{
char str[MAX_LEN], temp[MAX_LEN];
printf("Enter the Sentence to print reverse : ");
scanf("%[^\n]%*c", &str);
int i, left, right, length = strlen(str);
left = 0;
right = length - 1;
printf("%d \n", length);
for(i=0;i<length;i++)
{
temp[i] = str[right];
right--;
}
printf("%s",temp);
return 0;
}

Processing outputs of multiple inputs in C

It's not something trivial but I would like to know the best way to process multiple outputs, for example:
Input
First line of input will contain a number T = number of test cases. Following lines will contain a string each.
Output
For each string, print on a single line, "UNIQUE" - if the characters are all unique, else print "NOT UNIQUE"
Sample Input
3
DELHI
london
#include<iostream>
Sample Output
UNIQUE
NOT UNIQUE
NOT UNIQUE
So how can I accomplish outputs like that? My code so far is:
int main(int argc, char *argv[])
{
int inputs, count=0;
char str[100];
char *ptr;
scanf("%d",&inputs);
while(inputs-- >0)
{
scanf("%s",str);
for(ptr=str; *ptr!='\0';ptr++)
{
if( *ptr== *(ptr+1))
{
count++;
}
}
if(count>0)
{
printf("NOT UNIQUE");
}
else
{
printf("UNIQUE");
}
}
}
But the above will obviously print the output after each input, but I want the output only after entering all the inputs, if the user enters 3, then the user have to give 3 strings and after the output will be given whether the given strings are unique or not. So I want to know how can I achieve the result given in the problem. Also another thing I want to know is, I am using an array of 100 char, which it can hold a string up to 100 characters, but what do I have to do if I want to handle string with no limit? Just declaring char *str is no good, so what to do?
Hope this helps:
#include <stdio.h>
int main(int argc, char *argv[])
{
int inputs,count=0;
char str[20];
scanf("%d",&inputs);
char *ptr;
char *dummy;
while(inputs-- >0)
{
scanf("%s",str);
for(ptr=str; *ptr!='\0';ptr++)
{
for(dummy=ptr+1; *dummy != '\0';dummy++)
{
if( *ptr== *dummy)
{
count=1;
}
}
if(count == 1)
break;
}
if(count>0)
{
printf("NOT UNIQUE");
}
else
{
printf("UNIQUE");
}
}
}
If you want to save stuff for later use, you must store it somewhere. The example below stores up to 10 lines in buf and then points str to the current line:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* for strlen */
#include <ctype.h> /* for isspace */
int main(int argc, char *argv[])
{
int ninput = 0;
char buf[10][100]; /* storage for 10 strings */
char *str; /* pointer to current string */
int i;
printf("Enter up to 10 strings, blank to and input:\n");
for (i = 0; i < 10; i++) {
int l;
str = buf[i];
/* read line and break on end-of-file (^D) */
if (fgets(str, 100, stdin) == NULL) break;
/* delete trailing newline & spaces */
l = strlen(str);
while (l > 0 && isspace(str[l - 1])) l--;
str[l] = '\0';
/* break loop on empty input */
if (l == 0) break;
ninput++;
}
printf("Your input:\n");
for (i = 0; i < ninput; i++) {
str = buf[i];
printf("[%d] '%s'\n", i + 1, str);
}
return 0;
}
Note the two separate loops for input and output.
I've also rejiggled your input. I'm not very fond of fscanf; I prefer to read input line-wise with fgets and then analyse the line with strtok or sscanf. The advantage over fscanf is that yout strings may contain white-space. The drawback is that you have a newline at the end which you usually don't want and have to "chomp".
If you want to allow for longer strings, you should use dynamic allocation with malloc, although I'm not sure if it is useful when reading user input from the console. Tackle that when you have understood the basics of fixed-size allocation on the stack.
Other people have already pointed you to the error in your check for uniqueness.

Resources