I have written a code trying to split a long string to get simpler strings so that i could sort them out... When i break from the nested loop, does it break up to the first loop entirely??
My input is "&$(, My,na$me(is"
the output that i wanted is "My na me is"
How can i solve this??
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char splitter[100];
char mystring[1000];
char newstring[1000][1000];
int i,j,z,k=0;
scanf("%s", splitter);
scanf("%s", mystring);
for (i=0; i<1000; i++){
for (j=k; j<1000; j++){
for (z=0; z<100; z++){
if (mystring[j]==splitter[z]){
k++;
break;
}
else
{
newstring[i][j]=mystring[j];
}
}
if (mystring[j]==splitter[z])
break;
}
}
for (i=0; i<10; i++){
printf("%s ", newstring[i]);
}
return 0;
}
First; C is not Python, you can't just use indent to denote blocks, you must use braces, i.e. { and }.
Second, no a break only breaks the closest-most loop its in, there's no way to break out of more than one level.
Third, you're looping over the strings as if they're always 100 characters long which they won't always be (for instance in your example they're not). This is wrong, you should use strlen() to figure out how long they are.
Fourth, you should check the return values of your scanf() calls, since it can fail.
Fifth, newstring is declared as an array of arrays, i.e. a gigantic one-megabyte 2D "square" of characters, which is clearly not how you're using it.
#include <stdio.h>
#include <string.h>
int main(){
char splitter[100];
char mystring[1000];
char *tokens[500];
char *token;
int i=0;
scanf("%99[^\n]%*c", splitter);
scanf("%999[^\n]", mystring);
token = strtok(mystring, splitter);
while(token){
if(i)
putchar(' ');
printf("%s", token);
tokens[i++] = token;
token = strtok(NULL, splitter);
}
putchar('\n');
return 0;
}
Though there are many mistakes in your code and I am unable to find out why are you doing those mistakes.For example I dint get why are you scaning two arrays and why are you using a two-D array.Another thing I would like to tell you is that scanf doesnt work when there is spaces in the string.According to your problem here is very simple solution.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char splitter[100];
char mystring[1000];
char newstring[1000][1000];
int i,j,z,k=0;
gets(splitter);
for(i=0;i<strlen(splitter);++i){
if(((splitter[i])>=65 &&(splitter[i]<=90)) || ((splitter[i]>=97)&&(splitter[i] <=122)))
mystring[k++]=splitter[i];
else
mystring[k++]=' ';
}
printf("%s\n",mystring);
//scanf("%s", mystring);
return 0;
}
Check the below code:
int main()
{
int i=0,j=0,t,f=0;
char s[20];
char b[20];
printf("Enter the string\n");
scanf("%s",&s);
while(s[i] != '\0')
{
t = s[i];
if((t>=65 && t<=90) || (t>= 97 && t<=122))
{
b[j++] = s[i];
f = 1;
}
else
{
if(f)
b[j++] = ' ';
}
i++;
}
b[j] = '\0';
printf("%s\n",b);
return 0;
}
Related
Task is to add * after every * in string:
Input:*fsd*fds*fds*f
Output: **fsd**fds**fds**f
I found this and i am trying to replace every * with **
But it wont work.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <string.h>
int main() {
char x[256];
scanf("%s", &x);
for (char* p = x; p = strchr(p, '*'); ++p) {
*p = '*';
}
printf("%s", x);
system("pause");
return 0;
}
it only works when i use one char in this line
*p = '*';
but when i use more it does not work.
so *p = '**'; does not work.
Thanks for any help or hint.
It's easier to write the code if you just read one character at a time like this:
#include <stdio.h>
int main() {
while (1) {
int input = fgetc(stdin);
if (input == EOF) { break; }
if (input == '*') { fputc('*', stdout); }
fputc(input, stdout);
}
}
Also, since we are not dealing with memory allocations, arrays, or strings here, it is a lot easier to write safe code that will not suffer from buffer overflow bugs.
Note: Recent versions of the C standard put return 0; implicitly at the end of your main function so you don't have to write it yourself.
As I mentioned in the comments, when you replacing * with ** you are writing two characters in place of one, so it replaces the next character after *. One otherway would be to take another empty array and copy elements from input string, when you find * you can insert two ** Following snippet shows one potential solution.
#include<stdio.h>
#include <string.h>
int main() {
char x[256],y[256];
unsigned index = 0;
scanf("%s", x);
for (unsigned i = 0; i < strlen(x); i++) {
y[index++] = x[i];
if(x[i] == '*')
y[index++] = '*';
}
y[index] = '\0';
printf("%s", y);
system("pause");
return 0;
}
I have I problem. I get 2 warnings from console, but I dont know what's wrong with my code. Can you have look?
Program suppose to show lines with at least 11 characters and 4 numbers
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
if(isalpha(line)) numberAlpha++;
else if(isdigit(line)) numberDigit++;
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Both isalpha() and isdigit() takes an int, not a char *, as argument.
In your code, by passing the array name as the argument, you're essentially passing a char * (array name decays to the pointer to the first element when used as function argument), so, you're getting the warning.
You need to loop over the individual elements of line and pass them to the functions.
That said, just a suggestion, for hosted environment, int main() should be int main(void) to conform to the standard.
isalpha and isdigit are supposed to test if a char taken as int (a char can be safely converted to an int) is the encoding of an alphanumeric or digit character. You pass a char array, not an individual char. You need to test each char of the string you got, so you need a loop as:
for (int i=0; i<strlen(line); i++) {
if (isalpha(line[i])) numberAlpha++;
...
}
It is better to compute the length once:
int length = strlen(line);
for (int i=0; i<length; i++) {
...
}
You may also use a pointer to move along the string:
for (char *ptr = line; *ptr!=`\0`; ptr++) {
if (isalpha(*ptr)) ...
...
}
isalpha() and isdigit() functions take an int. But you are passing a char* i.e. the array line gets converted into a pointer to its first element (see: What is array decaying?). That's what the compiler complains about. You need to loop over line to find the number of digits and alphabets in it.
Also note that fgets() will read in the newline character if line has space. So, you need to trim it out before counting.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
line[strcspn(line, "\n")] = 0; // Remove the trailing newline, if any.
for (size_t i = 0; line[i]; i++) {
if(isalpha((unsigned char)line[i])) numberAlpha++;
else if((unsigned char)isdigit(line[i])) numberDigit++;
}
printf("alpha: %d, digits:%d \n", numberAlpha, numberDigit);
}
return 0;
}
Ok, i got something like this:
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
int i;
for(i=0; i<strlen(line); i++){
if(isalpha(line[i])) numberAlpha++;
else if(isdigit(line[i])) numberDigit++;
}
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Now the question is, if it is passible to make it first accepts data and then display only those line which follows the if statment. Now it shows line just after input it.
I am trying to take a user inputted string and look at each code to see if it appears in another string of strings. So far my code works.
If the word is successfully found then the alpha representation is to be added to an array that will eventually be printed, but only if all codes were found.
I am having issues with what gets stored in my array that is going to be printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char *string;
typedef char *alpha;
int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);
do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';
for (x=0;x<4;x++)
{
printf("value of x %d\n",x);
ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);
prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");
}
}
j = 0;
}
i++;
}while(input[i] !='\0');
for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}
return 0;
free(input);
}
The problem you asked about is caused by the way prntArr is used in the program. It really should be an array of character pointers into the alpha array. Instead, it's manipulated as an array of characters into which the first character of each morse code element is stored. And when it's printed, the variable that tracks how much of the array is used is simply ignored.
Another problem is that your code uses spaces to break the codes but there won't necessarily be a space at the end of the line so a code might get missed. In the program below, I switched out scanf() for fgets() which leaves a newline character on the end of the input which we can use, like space, to indicate the end of a code.
Other problems: you print the invalid Morse code message at the wrong point in the code and you print it to stdout instead of stderr; you remember to free input but forget to free hold; you put code after return that never gets called.
Below is a rework of your code that addresses the above problems along with some style issues:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("please enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code: %s\n", hold);
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s ", print_array[x]);
}
printf("\n");
return 0;
}
SAMPLE RUNS
> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>
> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>
i have a string that is made out of a few sentences.
for example:
hello world bye bye
now, i need to make this sentence into a coulmn of words:
hello
world
bye
bye
i have this idea going on, but i dont know how to write it correctly, so i was hopiny ypu guys could help me out.
this is what i have so far:
int len=0, k=0, stopatspace=0;
char temptext[100][15]={0};
char line[300]={0};
len=strlen(line);
printf("len is: %d", len);
for(k=0; k<len; k++)
{
if (k == ' ')
{
// i dont know what to write here in order to make it a cloumn
}
}
basiclly, my idea is to run on all the length of my line and when i reach a space i want it to enter (to go one line down so that it will look like a coulmn)
Suppose line is the char array that contains hello world bye bye and text is declared as
char text[100][15]; //I used 100 and 15 because your example contains it
and you want each word to be copied into each row of text. Then,use strtok() function with " "(space) as delimeter and place this in a loop that terminates when strtok() returns NULL to get each word. Copy each word to each row of text using strcpy() in the loop.
The code for this will look like this:
char text[100][15];
char line[]="hello world bye bye";
int i=0;
char *token=strtok(line," ");
while(token!=NULL)
{
strcpy(text[i],token);
i++;
token=strtok(NULL," ");
}
Now, to print it,you can use
for(int j=0;j<i;j++)
printf("text[%d]=%s",j,text[j]);
Another method would be to manually copy each character until a space is seen.
int len=strlen(line);
int i=0;
int k=0;
for(int j=0;j<len+1;j++)
{
if(line[j]==' ')
{
text[i][k]='\0';
i++;
k=0;
}
else
{
text[i][k]=line[j];
k++;
}
}
Note that the above code does not prevent buffer overflows. You can print each word using
for(int j=0;j<i+1;j++)
printf("text[%d]=%s",j,text[j]);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[100];
fgets(string, 100, stdin);
string[strlen(string)-1] = 0;
// create an array of pointers
char **string_array = (char**)malloc(sizeof(char*));
int i = 0, array_size;
// tokenize input
char *token = strtok(string, " ");
while(token!=NULL) {
// dynamically increase the array during run time
string_array = (char**)realloc(string_array, (i+1)*sizeof(char**));
// create the string as you would do when there is only one string
string_array[i] = (char*)malloc(strlen(token)+1);
strcpy(string_array[i], token);
token = strtok(NULL, " ");
i++;
}
array_size = i;
for(i=0; i<array_size; i++) {
printf("%s\n", string_array[i]);
}
return 0;
}
Basically you create an array of pointers and you allot memory for the strings one by one as you would do when there is only one string.
(if number of token is unknown, use realloc to increase the size of pointer to pointers.)
#include <stdio.h>
#include <ctype.h>
int main(void){
char line[300] = "hello world bye bye\n";
char temptext[100][15]={0};
int i=0, j, k=0;
while(line[k]){
if(isspace(line[k])){
++k;//skip space to word
continue;
}
for(j=0; j < 15-1 && line[k] && !isspace(line[k]); ++k, ++j)
temptext[i][j] = line[k];
if(j && ++i == 100)
break;
}
for(j=0; j<i; ++j)
puts(temptext[j]);
return 0;
}
#include<stdio.h>
#define NEWLINE printf("\n")
int main(void)
{
char string[]="hello world bye bye";
int index=0;
while(string[index])
{
if(string[index]==32)
{
NEWLINE;
index++;
}
else
{
printf("%c",string[index]);
index++;
}
}
NEWLINE;
}
// Whenever i encountered with a space, i am printing a new line on the screen. Here 32 is the ASCII value for space
So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!