For the most part everything is working and it's able to build error free. However when I try to run it, it seems to crash. To be more specific, whenever I start my code and press 'a' or 'b', the program keeps crashing. Can someone tell me how to fix that?
#include <stdio.h>
#include <string.h>
int top=-1;
int word;
char stack_string[100];
void push(char word);
char pop(void);
int main()
{
char input;
char str[100];
int i;
printf("press [a] for palindrome check, [b] for string reversal:");
scanf("%s", input);
if (input == 'b'){
printf("Input a string: ");
scanf("%[^\n]s", str);
for(i=0;i<strlen(str);i++)
push(str[i]);
for(i=0;i<strlen(str);i++)
str[i]=pop();
printf("Reversed String is: %s\n",str);
}
else if(input == 'a'){
char str[100];
int count = 0;
printf("Input a string: ");
scanf("%[^\n]s", str);
for (i = 0; i < strlen(str); i++)
{
push(str[i]);
}
for (i = 0; i < strlen(str); i++)
{
if (str[i]==pop())
count++;
}
if (count == strlen(str))
printf("%s is a palindrome\n", str);
else
printf("%s is not a palindrome\n", str);
}
return 0;
}
void push(char word)
{
top=top+1;
stack_string[top]=word;
}
char pop()
{
word = stack_string[top];
top=top-1;
return word;
}
the main problem is input stream
for single char input in scanf
we use scanf( "%c", &input);
but for whole non-space array of characters / string we use
scanf( " %s", str);
for string contains whitespace except new line
gets_s( str, sizeof( str ) ) ;
for your case
correct the following code
scanf( "%s", input);
to
scanf( "%c", &input);
Happy Coding
main problem is you are reading a string but comparing it to a single char
that's why if condition is not working
just convert
scanf( "%s", input);
to
scanf( "%c", &input);
that will be enough
The problem is: you are getting the input with scanf("%s", input);
therefore the condition input == 'a' is the same as "a" == 'a' which never meets
you need to get the input as a char using
scanf("%c", &input);
not
scanf("%s", input);
Related
My program is supposed to count in a string an entered string.
For example:
Enter a text: Hello World
Enter a string: llo
occurs 1 times in Hello World
Unfortunately, my program does not give me anything.
Does anyone have a tip for me?
void aufgabe7(char string[MAX], char stringw[MAX]){
printf("Enter a Text: \n");
fgets(string, MAX, stdin);
int i, j, len, len2;
int count = 0;
int count2 = 0;
len = strlen(string);
printf("Enter a string: \n");
fgets(stringw, MAX, stdin);
len2 = strlen(stringw);
for (i = 0; i < len;)
{
j = 0;
count = 0;
while ((string[i] == stringw[j]))
{
count++;
i++;
j++;
}
if (count == len2)
{
count2++;
count = 0;
}
else
i++;
}
printf("%s occurs %d times in %s \n", stringw, count2, string);
}
void main (void){
char data[MAX];
task7(&data[0], &data[0]);
}
As commenter #Steve Summit noted, you are searching for a string read from fgets, which has a trailing newline. Normally, you would need to remove the newline from the input from fgets, otherwise it is part of the searched for string. The simplest way to do this is to call buffer[strcspn(buffer, "\n")] = '\0'; as documented in this question.
However, I feel the correct answer to this question is that there is a more idiomatic way of doing this with C than comparing char by char: using strstr with pointer arithmetic will work just as well and is cleaner to read:
char input[SIZE];
char search[SIZE];
size_t count = 0;
printf("Enter a phrase: ");
fgets(input, SIZE, stdin);
input[strcspn(input, "\n")] = '\0';
printf("\nEnter a sub-phrase: ");
fgets(search, SIZE, stdin);
search[strcspn(search, "\n")] = '\0';
char *p = input;
while((p = strstr(p, search)) != NULL)
{
printf("Found occurrence of '%s' at position %td\n", search, (ptrdiff_t)(p - input));
count++;
p++;
}
printf("Found %zu occurrences of '%s'.\n", count, search);
I've been getting the error: "subscripted value is neither an array nor pointer nor vector" for my code on line 14. It seems like it should be able to compare the value in the array to the char since they are both primitive data yet I can't seem to get it right:
#include <stdio.h>
#include <string.h>
char str[80];
char ch;
int cnt =0;
int suffix ( str, ch) {
int i=0;
while (strchr(str+i, ch) != NULL){
if (ch == str[i] ){
printf("\n %s \n", str+i);
cnt += 1;
}
i++;
}
return cnt;
}
int main() {
printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);
printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%s", str);
printf("\n The String you typed in is: %s.", str);
suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;
}
The problem is that you are declaring the function like this:
int suffix ( str, ch)
{
...
}
without telling the compiler the type of str and ch. So the compiler assumes
they are int, and you cannot use [] on an int. You have to declare the
functions like this
int suffix(char *str, char ch)
{
...
}
And why are you declaring str, ch and cnt as global variables? There is
absoulutly no reason for that.
So the program should look like this:
#include <stdio.h>
#include <string.h>
// const char is even better, because you are not modifying the string
int suffix (const char *str, char ch) {
int cnt = 0;
int i=0;
while (strchr(str+i, ch) != NULL){
if (ch == str[i] ){
printf("\n %s \n", str+i);
cnt += 1;
}
i++;
}
return cnt;
}
void clean_stdin(void)
{
int ch;
while((ch = getchar()) != '\n' && ch != EOF);
}
int main() {
int ch;
int cnt;
char str[100];
printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);
clean_stdin(); // to get rid of the newline in the input buffer
// or if the user typed more than a single character
printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%99s", str);
printf("\n The String you typed in is: %s.", str);
cnt = suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;
}
When I try to run the scanf inside of the if function after entering either 'a' or 'b', it immediately runs and exits the program without getting input. Is there a way to fix it so the scanf works inside of the if and else if functions?
#include <stdio.h>
#include <string.h>
int top=-1;
int word;
char stack_string[100];
void push(char word);
char pop(void);
int main()
{
char input;
char str[100];
int i;
printf("press [a] for palindrome check, [b] for string reversal:");
scanf("%c", &input);
if (input == 'b'){
printf("Input a string: ");
scanf("%[^\n]s", str);
for(i=0;i<strlen(str);i++)
push(str[i]);
for(i=0;i<strlen(str);i++)
str[i]=pop();
printf("Reversed String is: %s\n",str);
}
else if(input == 'a'){
char str[100];
int count = 0;
printf("Input a string: ");
scanf("%[^\n]s", str);
for (i = 0; i < strlen(str); i++)
{
push(str[i]);
}
for (i = 0; i < strlen(str); i++)
{
if (str[i]==pop())
count++;
}
if (count == strlen(str))
printf("%s is a palindrome\n", str);
else
printf("%s is not a palindrome\n", str);
}
return 0;
}
void push(char word)
{
top=top+1;
stack_string[top]=word;
}
char pop()
{
word = stack_string[top];
top=top-1;
return word;
}
Use this:
scanf(" %[^\n]s", str);
^^^
Whitespace
instead of
scanf("%[^\n]s", str);
For more information, refer this link.
Stop using scanf(). The terminal sends your application a full line at a time, but scanf() only consumes the parts it needs, i.e. one character in the case of %c or just all the digits in case of %d. The rest is left in the input buffer, where the following scanf() get them. That causes the user's input and what the program receives to be somewhat "out of sync".
It's better to read full lines at a time, with fgets() or getline(), and then parse whatever you want from them. E.g.:
#define LINELEN 255
char line[LINELEN];
fgets(line, LINELEN, stdin);
int num;
int a = sscanf(line, "%d", &num);
Use whatever format string you require on the sscanf() and put the whole thing in a function if you like. (LINELEN there is of course an arbitrary
limit, but fgets() requires some limit.)
See also: http://c-faq.com/stdio/scanfprobs.html and the longer explanation linked there.
use scanf like this: scanf("%s", str)
Only scanf statements need to be changed:
#include <stdio.h>
#include <string.h>
int top=-1;
int word;
char stack_string[100];
void push(char word);
char pop(void);
int main()
{
char input;
char str[100];
int i;
printf("press [a] for palindrome check, [b] for string reversal:");
scanf("%c", &input);
if (input == 'b'){
printf("Input a string:\n");
scanf("%s", str);
for(i=0;i<strlen(str);i++)
push(str[i]);
for(i=0;i<strlen(str);i++)
str[i]=pop();
printf("Reversed String is: %s\n",str);
}
else if(input == 'a'){
char str[100];
int count = 0;
printf("Input a string:\n");
scanf("%s", str);
for (i = 0; i < strlen(str); i++)
{
push(str[i]);
}
for (i = 0; i < strlen(str); i++)
{
if (str[i]==pop())
count++;
}
if (count == strlen(str))
printf("%s is a palindrome\n", str);
else
printf("%s is not a palindrome\n", str);
}
return 0;
}
void push(char word)
{
top=top+1;
stack_string[top]=word;
}
char pop()
{
word = stack_string[top];
top=top-1;
return word;
}
Is it possible to scan a character, pass it to a char array and then if a is defined as string to print that string? Below is the code, (which gets the warning "cast to pointer from integer of different size")
Thanks in advance
char *a = "alpha";
int main()
{
char *A[80];
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = (char *) ch;
printf("%s\t", A[0]);
return 0;
}
What you want might be something like this.
#include <stdio.h>
/* word candidate list: terminated by NULL */
const char* a[] = {
"alpha",
NULL
};
int main(void)
{
char ch;
int i;
/* read input */
printf("enter message");
if (scanf(" %c", &ch) != 1)
{
puts("read error");
return 1;
}
/* search for matching word(s) */
for (i = 0; a[i] != NULL; i++)
{
/* if the first character of the word is what is scanned, print the word */
if (a[i][0] == ch)
{
printf("%s\t", a[i]);
}
}
return 0;
}
Here's what you probably meant to write:
int main()
{
char A[80];
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = ch;
printf("%c\t", A[0]);
return 0;
}
You didn't declare you array A right, and when you print a char (A[0]), you should use %c in printf() function.
If you wanted to print it as an string (%s modifier), you need to NULL-terminate it, which means adding \0 at the end of the string.
If you want to create a string from a char and print it using "%s" then, you need to do something like below:
char *a = "alpha";
int main()
{
char A[80] = {0};
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = ch;
printf("%s\t", A);
return 0;
}
The mistakes in your code were:
You were declaring an array of char pointers instead of an array of
char
You were assigning a char typecasted as char *
Your print statement was incorrect due to the declaration of char
array being wrong.
Please note that I have initialized the array A to 0, so that the string is automatically null terminated.
Based on your comment, the updated code for your expected solution:
char *a = "alpha";
int main()
{
char ch;
printf("enter message");
scanf(" %c", &ch);
if (ch == 'a')
printf("%s\t", a);
return 0;
}
Try this code, I'm now on mobile phone. I haven't tested it.
int main()
{
char A[80];
char ch;
printf("enter message");
A[0] = (char)fgetc(stdin);
printf("\n%c\n", A[0]);
return 0;
}
I am trying to input string into fixed size char array.
I have a questions:
when I input a string which is bigger than the char array, the array become bigger without any additional declaration. I want to make the code only take the string that 'equal or smaller than the char array'.
Thank You.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/***************************Function****************************/
int string_length(char s[]) {
int c = 0;
while (s[c] != '\0')
c++;
return c;
}
/**************************************************************/
char *str;
int arrSize;
void opt1()
{
printf("Enter array size: ");
scanf("%d", &arrSize);
arrSize=arrSize+1;
str = malloc(arrSize);
return;
}
void opt2()
{
printf("Enter characters: ");
scanf("%s", str);
length = string_length(str);
printf("your input is '%s'\n", str);
printf("your input length is '%d'\n", length);
return;
}
int main()
{
int input = 0;
while(input != 3) {
printf("\n NAME \n");
printf("\n");
printf("--------------------------------------\n");
printf("1) Making Array \n");
printf("2) Check Array \n");
printf("3) Quit\n");
printf("\nEnter selection: ");
scanf("%d", &input);
if( input == 1 ) {
/* */
opt1();
}
else if(input == 2) {
opt2();
}
}
return 1;
}
OP wants to read data, yet if larger that the target array, then do not change the target array.
// 1: success
// -1 EOF
// 0: Input too long
int read_array(char *buffer, size_t size) {
char tmp[size];
size_t i = 0;
int ch;
while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
if (i < size) {
tmp[i++] = ch;
}
}
if (ch == EOF && i == 0) return EOF;
if (i >= size) return 0; // too many
memcpy(buffer, tmp, i);
buffer[i] = '\0';
return 1;
}
Normally code could use fgets(), but there are corner cases that fail to meet OP goals.
To read in a whole line, you can use fgets:
char line[80];
if (fgets(line, sizeof line, stdin) != NULL) {
// use the input
}
Now you won't need to check if the user entered more than the limit, since fgets will only get the first 79 (-1 for null terminator) characters; the remainder, if any, will be ignored.