Print "no solution" if there's no input - c

I tried modifying this code to print
no solution
if there is no input by user. That is, if I run the program and simply press enter it should print no solution. I added the code that's meant to do that to check if the string length is 0 then print but it doesn't work
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i, j, ctr;
fgets(str1, sizeof str1, stdin);
j = 0; ctr = 0;
if (strlen(str1) == 0) {
printf_s("no solution");
}
else
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 if (str1[i] == '.' || str1[i] == ',')
{
newString[ctr][j] = '\0';
ctr--; //for next word
j = - 1;
}
else
{
newString[ctr][j] = str1[i];
j++;
}
}
printf("\n\n");
for (i = 0; i < ctr; i++)
printf(" %s\n", newString[i]);
return 0;
}

fgets() will add a new line to your string (see this link for more information) which means when you simply press enter your string length(since your string includes \n) is 1 , you should say:
if (strlen(str1) == 1) {
printf_s("no solution");
// it's better to add a return 0; here if you don't want to continue the program
}
or use this instead:
if (!strcmp(str1,"\n")) {
printf_s("no solution");
}

Related

String Pattern Matching in C

I was trying this pattern matching method in C but whenever I give all the input, the vscode terminal waits for a while and just stops the program without any warnings/message. Can anyone point to what is wrong here?
#include <stdio.h>
#include <string.h>
int main()
{
char STR[100], PAT[100], REP[100], ANS[100];
int i, m, j, k, flag, slP, slR, len;
i = m = k = j = flag = len = 0;
printf("\nMain String: ");
gets(STR);
printf("\nPattern String: ");
gets(PAT);
slP = strlen(PAT);
printf("\nReplace String: ");
gets(REP);
slR = strlen(REP);
while (STR[i] != '\0')
{
if (STR[i] = PAT[j])
{
len = 0;
for (k = 0; k < slP; k++)
{
if (STR[k] = PAT[k])
len++;
}
if (len == slP)
{
flag = 1;
for (k = 0; k < slR; k++, m++)
ANS[m] = REP[k];
}
}
else
{
ANS[m] = STR[i];
m++;
i++;
}
}
if (flag == 0)
{
printf("\nPattern not found!");
}
else
{
ANS[m] = '\0';
printf("\nResultant String: %s\n", ANS);
}
return 0;
}
There are multiple problems in the code:
using gets() is risky, this function was removed from the C Standard because it cannot be used safely.
if (STR[i] = PAT[j]) copied the pattern to the string. You should use:
if (STR[i] == PAT[j])
similarly, if (STR[k] = PAT[k]) is incorrect. You should compare PAT[k] and STR[i + k]:
if (STR[i + k] == PAT[k])
you should test for buffer overflow for the output string as replacing a short string by a larger one may produce a string that will not fit in ANS
you do not increment i properly.
Here is a modified version:
#include <stdio.h>
int getstr(const char *prompt, char *dest, int size) {
int c, len = 0;
printf("%s", prompt);
while ((c = getchar()) != EOF && c != '\n') {
if (len + 1 < size)
dest[len++] = c;
}
if (size > 0)
dest[len] = '\0';
printf("\n");
if (c == EOF && len == 0)
return -1;
else
return len;
}
int main() {
char STR[100], PAT[100], REP[100], ANS[100];
int i, m, k, flag;
if (getstr("Main String: ", STR, sizeof STR) < 0)
return 1;
if (getstr("Pattern String: ", PAT, sizeof PAT) < 0)
return 1;
if (getstr("Replace String: ", REP, sizeof REP) < 0)
return 1;
i = m = flag = 0;
while (STR[i] != '\0') {
if (STR[i] == PAT[0]) { // initial match
// compare the rest of the pattern
for (k = 1; PAT[k] != '\0' && PAT[k] == STR[i + k]; k++)
continue;
if (PAT[k] == '\0') { // complete match
flag = 1;
// copy the replacement string
for (k = 0; REP[k] != '\0'; k++) {
if (m + 1 < sizeof ANS)
ANS[m++] = REP[k];
}
i += k; // skip the matching characters
continue;
}
}
// otherwise copy a single character
if (m + 1 < sizeof ANS)
ANS[m++] = STR[i];
i++;
}
ANS[m] = '\0';
if (flag == 0) {
printf("Pattern not found!\n");
} else {
printf("Resultant String: %s\n", ANS);
}
return 0;
}

Garbage value encounter in -C

In this code I have got a string input- "WUBABCWUBNAWBWUB".
here i need to remove the word "WUB" and print the remaining.Example: "ABC NAWB";
i have almost solved it but the problem is when i give the input(given above) I get a garbage value at the end.It shows: "ABC NAWB~#".I cant understand whats wrong with the code,please help me to remove those garbage values.
#include <stdio.h>
#include <string.h>
int main() {
char str[201], original[201];
int cnt = 0, i, j = 0;
int len = strlen(str);
gets(str);
for(i = 0; i < len-3; i++) {
if(str[i] == 'W' && str[i+1] == 'U' && str[i+2] == 'B' && i != len) {
if(i != 0 && i != len-3) {
original[cnt] = ' '; //here i changed "WUB" into a blank line
j++;
cnt++;
}
i = i+2;
} else {
original[j] = str[i];
cnt++;
j++;
}
}
printf("%c %c\n", original[j], original[j+1]);
printf("%s", original);
printf("\n\nj=%d,i=%d,cnt=%d", j, i, cnt);
}
A few modifications:
I have added a '\0' the end at the new string
I have modified the code such that it works even if the end is not equal to WUB (maybe useless modification)
I have removed the redundant j index
I have replaced the gets function with the more secure fgets
#include<stdio.h>
#include<string.h>
int main()
{
char str[201],original[201];
fgets(str, 200, stdin);
int cnt=0,i, len=strlen(str);
for(i = 0; i <= len-3; i++) {
if(str[i]=='W' && str[i+1]=='U' && str[i+2]=='B' && i!=len) {
if(i!=0 && i!=len-3) {
original[cnt++] = ' '; //here i changed "WUB" into a blank line
}
i = i+2; // to jump over the "WUB" word
} else {
original[cnt++] = str[i];
}
}
for (int j = i; j < len; j++) { // to deal with the case the string doesn't terminate with "WUB"
original[cnt++] = str[j];
}
original[cnt++] = '\0';
//printf("%c %c\n",original[cnt],original[cnt+1]);
printf("%s",original);
//printf("\n\n,i=%d,cnt=%d",i,cnt);
}
Strings are actually a one-dimensional array of characters terminated by a null character '\0'. so in your program original is a character array and once the values are assigned to it, at last '\0' should be there so adding just one line of code may help you get correct output.
original[j]='\0';
thanks guys,i've solved the problem.The problem was solved after giving
original[j]='/0';
after the loop.I also used the cnt integer to avoid blanks more than once.Here is my new code.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[201],original[201];
fgets(str,201,stdin);
int cnt=0,i,j=0,len=strlen(str);
for(i=0;str[i]!='\0';i++){
if(str[i]=='W' && str[i+1]=='U' && str[i+2]=='B')
{
if(i!=0 && i!=len-3&&cnt==0&&j!=0)
{
original[j] = ' ';
cnt++;
j++;
}
i=i+2;
}
else
{
original[j] = str[i];
cnt=0;
j++;
}
}
original[j]='\0';
printf("%s",original);
}

How to get words out of a string and put them in an string array ? In C

I basically have a sentence in a string and want to break it down word per word. Every word should go into an array of strings. I am not allowed to use strtok. I have this code but it doesn't work. Can someone help?
There is for sure something similar in the internet but I couldn't find anything...
int main(){
char s[10000]; // sentence
char array[100][100]; // array where I put every word
printf("Insert sentence: "); // receive the sentence
gets(s);
int i = 0;
int j = 0;
for(j = 0; s[j] != '\0'; j++){ // loop until I reach the end
for(i = 0; s[i] != ' '; i++){ // loop until the word is over
array[j][i] = s[i]; // put every char in the array
}
}
return 0;
}
Every word should go into an array of strings. I am not allowed to use
strtok.
Interesting problem which could be resolved in a compact algorithm.
It handles multiple spaces and punctuation marks specified in check(char c).
The most difficult part of the problem is to properly handle corner cases. We may have situation when words are longer more than WORD_LEN length or the number of words exceeds the capacity of the array.
Both cases are properly handled. The algorithm truncates the excessive words and parses only to the capacity of the array.
(BTW. Do not use gets: Why is the gets function so dangerous that it should not be used?)
Edit: The fully tested find_tokens function has been presented.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LEN 3 // 100 // MAX WORD LEN
#define NR_OF_WORDS 3 // 100 // MAX NUMBER OF WORDS
#define INPUT_SIZE 10000
int is_delimiter(const char * delimiters, char c) // check for a delimiter
{
char *p = strchr (delimiters, c); // if not NULL c is separator
if (p) return 1; // delimeter
else return 0; // not a delimeter
}
int skip(int *i, char *str, int skip_delimiters, const char *delimiters)
{
while(1){
if(skip_delimiters) {
if( (str[(*i)+1] =='\0') || (!is_delimiter(delimiters, str[(*i)+1])) )
break; // break on nondelimeter or '\0'
else (*i)++; // advance to next character
}
else{ // skip excess characters in the token
if( is_delimiter(delimiters, str[(*i)]) )
{
if( (str[(*i)+1] =='\0') || !is_delimiter(delimiters, str[(*i)+1]) )
break; // break on non delimiter or '\0'
else (*i)++; // skip delimiters
}
else (*i)++; // skip non delimiters
}
}
if ( str[(*i)+1] =='\0') return 0;
else return 1;
}
int find_tokens(int max_tokens, int token_len, char *str, char array[][token_len+1], const char *delimiters, int *nr_of_tokens)
{
int i = 0;
int j = 0;
int l = 0;
*nr_of_tokens = 0;
int status = 0; // all OK!
int skip_leading_delimiters = 1;
int token = 0;
int more;
for(i = 0; str[i] != '\0'; i++){ // loop until I reach the end
// skip leading delimiters
if( skip_leading_delimiters )
{
if( is_delimiter( delimiters, str[i]) ) continue;
skip_leading_delimiters = 0;
}
if( !is_delimiter(delimiters,str[i]) && (j < token_len) )
{
array[l][j] = str[i]; // put char in the array
//printf("%c!\n", array[l][j] );
j++;
array[l][j] = 0;
token = 1;
}
else
{
//printf("%c?\n", str[i] );
array[l][j] = '\0'; // token terminations
if (j < token_len) {
more = skip(&i, str, 1, delimiters); // skip delimiters
}
else{
more = skip(&i, str, 0, delimiters); // skip excess of the characters in token
status = status | 0x01; // token has been truncated
}
j = 0;
//printf("more %d\n",more);
if(token){
if (more) l++;
}
if(l >= max_tokens){
status = status | 0x02; // more tokens than expected
break;
}
}
}
if(l>=max_tokens)
*nr_of_tokens = max_tokens;
else{
if(l<=0 && token)
*nr_of_tokens = 1;
else
{
if(token)
*nr_of_tokens = l+1;
else
*nr_of_tokens = l;
}
}
return status;
}
int main(void){
char input[INPUT_SIZE+1]; // sentence
char array[NR_OF_WORDS][WORD_LEN+1]; // array where I put every word, remeber to include null terminator!!!
int number_of_words;
const char * delimiters = " .,;:\t"; // word delimiters
char *p;
printf("Insert sentence: "); // receive the sentence
fgets(input, INPUT_SIZE, stdin);
if ( (p = strchr(input, '\n')) != NULL) *p = '\0'; // remove '\n'
int ret = find_tokens(NR_OF_WORDS, WORD_LEN, input, array, delimiters, &number_of_words);
printf("tokens= %d ret= %d\n", number_of_words, ret);
for (int i=0; i < number_of_words; i++)
printf("%d: %s\n", i, array[i]);
printf("End\n");
return 0;
}
Test:
Insert sentence: ..........1234567,,,,,,abcdefgh....123::::::::::::
tokens= 3 ret= 1
0: 123
1: abc
2: 123
End
You are not '\0'-terminating the strings and you are scanning the source from
the beginning every time you've found a empty character.
You only need one loop and, the inner loop and the condition must be s[i] != 0:
int j = 0; // index for array
int k = 0; // index for array[j]
for(i = 0; s[i] != '\0'; ++i)
{
if(k == 99)
{
// word longer than array[j] can hold, aborting
array[j][99] = 0; // 0-terminating string
break;
}
if(j == 99)
{
// more words than array can hold, aborting
break;
}
if(s[i] == ' ')
{
array[j][k] = 0; // 0-terminating string
j++; // for the next entry in array
k = 0;
} else
array[j][k++] = s[i];
}
Note that this algorithm doesn't handle multiple spaces and punctuation marks.
This can be solved by using a variable that stores the last state.
int j = 0; // index for array
int k = 0; // index for array[j]
int sep_state = 0; // 0 normal mode, 1 separation mode
for(i = 0; s[i] != '\0'; ++i)
{
if(k == 99)
{
// word longer than array[j] can hold, aborting
array[j][99] = 0; // 0-terminating string
break;
}
if(j == 99)
{
// more words than array can hold, aborting
break;
}
// check for usual word separators
if(s[i] == ' ' || s[i] == '.' || s[i] == ',' || s[i] == ';' || s[i] == ':')
{
if(sep_state == 1)
continue; // skip multiple separators
array[j][k] = 0; // 0-terminating string
j++; // for the next entry in array
k = 0;
sep_state = 1; // enter separation mode
} else {
array[j][k++] = s[i];
sep_state = 0; // leave separation mode
}
}
As you can see, using the sep_state variable I'm able to check if multiple
separators come one after the other and skips subsequent separators. I also
check for common punctuation marks.
#include <stdio.h>
int main()
{
char s[10000]; // sentence
char array[100][100]; // array where i put every word
printf("Insert sentence: "); // receive the sentece
gets(s);
printf("%s",s);
int i = 0;
int j = 0;
int k = 0;
for(j = 0; s[j] != '\0'; j++){ // loop until i reach the end
if ( s[j] != ' ' || s[j] == '\0' )
{
array[i][k] = s[j];
k++;
}
else {
i++;
k = 0;
}
}
return 0;
}
please note that the gets function is very unsafe and shouldn't in any case be used, use scanf or fgets instead

How do I do reverse sentence in this simple way?

I have a problem with this code which is supposed to make a reverse sentence.
Example:
Input
Hi my name is Robert
Output
Robert is name my Hi
#include <stdio.h>
#define LEN 50
int main(void)
{
char input, terminator = 0, sentence[LEN+1] = {0};
int i, j, last_space = LEN + 1, posc=0;;
int pos[]={0};
printf("\nEnter a sentence: ");
for (i = 0; (input = getchar()) != '\n'; i++)
{
if(input== ' '){
pos[posc]=i;
posc++;
}
if (input == '.' || input == '?' || input == '!')
{
last_space = i;
terminator = input;
break;
}
sentence[i] = input;
}
if (terminator == 0)
{
printf("Sentence needs a terminating character. (./?/!)\n\n");
return 0;
}
printf("Reversal of sentence: ");
for (i = last_space; i > 0; i--)
{
if (sentence[i] == ' ')
{
for (j = i + 1; j != last_space; j++)
{
putchar(sentence[j]);
}
last_space = i;
putchar(sentence[i]);
}
}
while (sentence[i] != '\0' && sentence[i] != ' ')
{
putchar(sentence[i++]);
}
printf("%c\n\n", terminator);
for(int i=sizeof(pos)-1; i>0; i--){
printf("%.*s", sentence[pos[i-1]], sentence[pos[i]]);
}
printf("%c\n\n", terminator);
return 1;
}
This keeps crashing because of the method at the bottom here:
printf("%c\n\n", terminator);
for(int i=sizeof(pos)-1; i>0; i--){
printf("%.*s", sentence[pos[i-1]], sentence[pos[i]]);
}
printf("%c\n\n", terminator);
return 1;
}
Can someone help me fix this snippet of code for me so that both methods work when run? Thanks.
The array of size 1 is created by the line:
int pos[]={0};
And later you are accessing over the array's limit here:
if(input== ' '){
pos[posc]=i;
posc++;
}
The behaviour is undefined after that. The same mistake presents in the code you've mentioned due to sizeof returns the size in bytes, not just amount of elements.
There is a simplest way to do it,
you just have to write a function who will write the last word of the sentence first, then the second and goes on ..
There you can find a working code
#include <unistd.h>
//This function print the last word or a space
static int print_last(const char *str, int len)
{
int i = 0;
while (len > 0 && str[len] == ' ')
len--;
while (i <= len && str[len - i] != ' ')
i++;
write(1, str + len - i + 1, i);
while (len > 0 && str[len] == ' ')
len--;
if (i < len)
write(1, " ", 1);
return (len - i);
}
int main(int ac, char **av)
{
int len = 0;
if (ac == 2)
{
while (av[1][len])
len++;
len--;
while (len > 0)
len = print_last(av[1], len);
}
write(1, "\n", 1);
return (0);
}
and there, once compiled (to compile --> clang yourFileName.c) , you can call the program like so
./youCompiledProgram 'the sentance you want to be inverted'

Compare code in reverse each word in sentence

I have school task. To reverse each word in sentence, so example :
Input: Fried chicken, fried duck.
Output: deirF nekcihc, deirf kcud.
So except dot and comma it's not reversed.
The first code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int i, n, titik = 0, coma = 0;
char s[5001];
char c[5001];
char *tok;
scanf("%[^\n]s", s);
if (s[0] == ' ')
printf(" ");
tok = strtok(s, " ");
while (tok != NULL) {
strcpy(c, tok);
n = strlen(c);
for (i = n; i >= 0; i--) {
if (c[i] == ',') {
coma = 1;
} else
if (c[i] == '.') {
titik = 1;
} else
printf("%c", c[i]);
}
if (coma) {
printf(",");
coma = 0;
} else
if (titik){
printf(".");
titik = 0;
}
tok = strtok(NULL," ");
if (tok == NULL)
printf("\n");
else
printf(" ");
}
}
Second code is
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
int i, j, n, prana = 0, titik = 0, coma = 0, end = 0;
char s[5001];
scanf("%[^\n]s", s);
n = strlen(s);
for (i = 0; i <= n; i++) {
if (isspace(s[i]) || iscntrl(s[i])) {
if (iscntrl(s[i]))
end = 1;
for (j = i - 1; j >= prana; j--) {
if (s[j] == '.') {
titik = 1;
} else
if (s[j] == ',') {
coma = 1;
} else
printf("%c", s[j]);
}
prana = i + 1;
if (titik) {
titik = 0;
if (end)
printf(".");
else
printf(". ");
} else
if (coma) {
coma = 0;
if (end)
printf(",");
else
printf(", ");
} else {
if (end)
printf("");
else
printf(" ");
}
}
}
printf("\n");
return 0;
}
Why the second code is accepted in test case?, but first code is not.
I tested the result it's same. Really identical in md5 hash.
The output of the two codes id different, because you print the terminating null character for each token in the first code. This loop:
for (i = n; i >=0 ; i--) ...
will have i == n in its first iteration. For a C string of length n, s[n] is the terminating null. This character may not show in the console, but it is part of the output.
To fix the loop, you could start with i = n - 1, but C uses inclusive lower bounds and exclusive upper bounds, and a more idomatic loop syntax is:
i = n;
while (i-- > 0) ...
Not related to your question at hand, but your codes are rather complicated, because they rely on many assumptions: words separated by spaces; only punctuation is comma or stop; repeated punctuation marks are ignored, special case for last word.
Here's a solution that treats all chunks of alphabetic characters plus the apostrophe as words and reverses them in place:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
void reverse(char *str, int i, int j)
{
while (i < j) {
int c = str[--j];
str[j] = str[i];
str[i++] = c;
}
}
int main()
{
char str[512];
int begin = -1;
int i;
if (fgets(str, sizeof(str), stdin) == NULL) return -1;
for (i = 0; str[i]; i++) {
if (isalpha((unsigned char) str[i]) || str[i] == '\'') {
if (begin == -1) begin = i;
} else {
if (begin != -1) {
reverse(str, begin, i);
begin = -1;
}
}
}
printf("%s", str);
return 0;
}

Resources