I've got an issue with my Enigma simulation [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
void character(){
int i=0;
char c;
printf("type your text to encode (max 80 chars):\n");
while((c=getchar()) != '\n')
{
text[i] = toupper(c);
i++;
}
text[i] = '\0';}
I'm using this piece of code in an emulator of Enigma. My problem is that the While instruction is always jumped, and I can't understand what's the problem and how to fix it!

Maybe there is something wrong with the declaration of the array text. This solution could clarify your question.
#include <stdio.h>
#include <ctype.h>
#define MAX_SIZE 10
int main(void) {
char text[MAX_SIZE];
int i = 0;
int c;
while ((c = getchar()) != '\n' && i <= MAX_SIZE - 2) {
text[i] = toupper(c);
i++;
}
text[i] = '\0';
printf("%s\n", text);
return 0;
}

As #trentcl mentioned, if there is a scanf prior to calling character() there is probably a newline left in the input stream. This will test for a leading newline and continue the loop.
The #define will set the size of the array so the loop does not put too many characters into text.
#define LIMIT 256
char text[LIMIT + 1] = {'\0'};
void character(){
int i = 0;
int c;
printf ( "type your text to encode (max 80 chars):\n");
while ( ( c = getchar ( )) != EOF)
{
if c == '\n') {
if ( i) {
break;//trailing newline
}
else {
continue;//leading newline
}
}
text[i] = toupper ( c);
i++;
if ( i >= LIMIT) {
break;
}
}
text[i] = '\0';
}

Related

A function to check if the word has an increasing or decreasing sequence of chars in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm new in C.
I've been asked to write a function that checks if the string has increasing/decreasing sequence of letters based on ASCII values + not includes white spaces(tabs,new lines etc.).
For example: demo is a very increasing string
beef is an increasing string
aa or zzz is an increasing string
tonic is a very decreasing string
spoon is a decreasing string
suddenly has no clear sequence.
So I wrote this code,it works but not so well..can you help me to improve it a little bit?
#include <stdio.h>
void f_sequence (char str[]);
int main()
{
char strl[101];
printf("your string is:\n");
scanf("%s\n", strl);
f_sequence(strl);
return 0;
}
void f_sequence(char str[])
{
int increase=0;
int decrease=0;
int match=0;
int i = 1;
if(!str[0])
printf("empty");
else if(!str[1])
printf("need more chars");
for(i=1; str[i]; i++)
{
if (str[i] == str[i-1])
match = 1;
if (str[i] > str[i-1])
increase = 1;
if (str[i] < str[i-1])
decrease = 1;
}
if((decrease==1) && (increase==0) && (match==0))
printf("we have a very descreasing sequence in here");
if((decrease==0) && (increase==1) && (match==0))
printf("we have a very increasing sequence in here");
if((decrease==1) && (increase==0) && (match==1))
printf("we have a descreasing sequence in here");
if((decrease==0) && (increase==1) && (match==1))
printf("we have an increasing sequence in here");
if((decrease==0) && (increase==0) && (match==1))
printf("we have an increasing sequence in here");
if((decrease==1) && (increase==1))
printf("not increasing and not decreasing");
puts("");
}
To ignore whitespaces, you can use isspace from <ctype.h> and skip in your calculations:
for(i = 1; str[i]; i++)
{
if (isspace((unsigned char)str[i])) continue;
...
}
But as is, you can't read input string with whitespaces as scanf with %s would stop reading at the first whitespace. You need fgets to read a line (so that you could read a string with whitespaces):
int main()
{
char strl[101];
printf("your string is:\n");
if (fgets(strl, sizeof strl, stdin)) {
char *p = strchr(strl, '\n');
if (p) *p = '\0'; // Remove newline if present
f_sequence(strl);
}
}
fgets would also read the newline character if there's space in the buffer which you may want to remove as shown (include <string.h> for strchr).
Use a function like below to remove whitespaces:
void removeSpaces(char *str)
{
// To keep track of non-space character count
int count = 0;
// Traverse the given string. If current character
// is not space, then place it at index 'count++'
for (int i = 0; str[i]; i++)
if (str[i] != ' ')
str[count++] = str[i]; // here count is
// incremented
str[count] = '\0';
}
And then add this function in the first line of f_sequence function. like this:
removeSpaces(str);

fgets() and sscanf() only stores first integer in array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was trying to terminate Integer array input using Enter key. So, I thought of using fgets and sscanf() but I have tried several approaches everytime i am getting first value only. Can someone help where I am doing wrong.
#include<stdio.h>
int main(){
int inp[100]={0};
int c=0,n;
char str[100]={0};
char *data = str;
while ((NULL != fgets(str, sizeof str, stdin)) && (str[0] != '\n')) {
if (1 != sscanf(str,"%d",&inp[c])) {
puts("Input was not an integer, try again.\n");
continue;
}
printf("\ninp[%d] = %d",c,inp[c]);
c++;
if (c >= 100) break;
}
}
I have added snap of my code and output -
Code
Output
%n is to capture the how many bytes have been read, thus you need to increment data n bytes to point to next number.
The below program reads all the integers till empty new line.
int main() {
int inp[100] = {0};
int c = 0, n = 0;
char str[100] = {0};
char *data = str;
while ((NULL != fgets(str, sizeof str, stdin)) && (str[0] != '\n')) {
data = str;
n = 0;
while (1 == sscanf(data, "%d%n", &inp[c], &n) && c < 100) {
printf("\ninp[%d] = %d\n", c, inp[c]);
data += n;
c++;
}
}

Program C count words (excluding numbers) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have come across a lot of counting words examples (like the one in the link below):
Counting words in a string - c programming
if(str[i]==' ')
{
i++;
}
and for digit is:
if(str[i]>='0' && str[i]<='9')
{
i++;
}
but what if the input were 'I have 12 apples.' and I only want the output to show "word count = 3"?
Assuming that you don't have words that contain alphanumeric combinations, like "foo12", then you could combine your code snippets, like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Bex 67 rep";
int len = strlen(str);
int count = 0, i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ')
{
if(i + 1 < len && ! (str[i + 1] >= '0' && str[i + 1] <= '9') && str[i + 1] != ' ')
count++;
}
i++;
}
printf("Word count = %d\n", count + 1); // Word count = 2
return 0;
}
where you loop over every character of the string, and when you find a whitespace, you check - if you are not at the last character of the string - if the next character is not a digit or a whitespace. If that's the case, then you can assume that the whitespace you encountered is precedended of a word, thus incease count.
Notice however that usually senteces do not start with a whitespace (which is an extra assumption for this answer), thus the number of words is one more than count.
In real life, use strtok() and check every token for its validity, since that's approach is just for demonstration and should be considered a bad approach.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="I have 12 apples";
char * pch;
unsigned long ul;
int cnt=0;
pch = strtok (str," ,.-");
while (pch != NULL)
{
ul = strtoul (pch, NULL, 0);
pch = strtok (NULL, " ,.-");
printf("%d\n", ul);
if(ul == 0)
cnt++;
}
printf("count is %d\n", cnt);
return 0;
}
String tokens parsed using strtok function.
My five cents.:)
#include <stdio.h>
#include <ctype.h>
size_t count_words( const char *s )
{
size_t n = 0;
const char *p = s;
while ( 1 )
{
int pos = 0;
sscanf( p, "%*[ \t]%n", &pos );
p += pos;
if ( sscanf( p, "%*s%n", &pos ) == EOF ) break;
if ( isalpha( ( unsigned char )*p ) ) ++n;
p += pos;
}
return n;
}
int main(void)
{
char s[] = "I have 12 apples";
printf( "The number of words is %zu\n", count_words( s ) );
return 0;
}
The program output is
The number of words is 3
And my advice is do not use the standard function strtok for such a task. First of all it may not deal with string literals. And it has a side effect of changing the original string.:)

Multiplying the numbers of a String [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to multiply the numbers in a given string which has one or more spaces.
Example:
If i input 52 26 23
the output should be 31096.
I've written this code but its not working:
#include <stdio.h>
int main()
{
char input[30];
int i, num = 0, v = 1;
gets(input);
for (i = 0; input[i] != '\0'; i++)
{
if(input[i] == 32)
{
v = v * num;
if(input[i+1] != 32)
{
num = 0;
continue;
}
}
num = (num * 10) + (input[i] - 48);
}
printf("%d",v);
return 0;
}
Try this one
#include <stdio.h>
#include <string.h>
int main()
{
char str[30];
char *token;
long int mul = 1;
gets(str);
token = strtok(str, " ");
while (token != NULL)
{
mul = mul * atoi(token);
token = strtok(NULL, " ");
}
printf("%ld",mul);
return 0;
}
The problem lies in your nested if statement. Once it enters the first if statement, that means input[i]==32, therefore it can never enter the next if statement where input[i]!=32.
I also have some suggestions for improving readability. Instead of using numbers to represent the characters, use the character literals themselves!
Another thing, you only have space for 30 characters in your input buffer. If a user attempts to enter more than this, you will have a buffer overflow.
Lastly, if the user puts more than one space between numbers, the output will become 0. That may be something you may or may not want to handle.
Edit: Before, the call to gets was only grabbing characters up to the first whitespace character. I've fixed this issue with a format string in a call to scanf instead. Buffer overflow problem still applies. Also, it was not multiplying with the last parsed integer, so I added code for that after the loop. Another note, this will only work for non-negative integers, if that's something you weren't aware of initially. The code just assumes the input is nice.
Edit 2: support for input with any number of spaces before, between, or after inputs.
#include <stdio.h>
int main() {
char input[30];
int i, num = 0, v = 1;
scanf("%[^\n]s", input);
// skip leading spaces
for(i = 0; input[i] == ' '; i++);
// parse remaining input
while(input[i] != '\0') {
if(input[i] == ' ') {
v *= num;
num = 0;
// skip subsequent spaces
while(input[++i] == ' ');
continue;
}
num *= 10;
num += input[i] - '0';
i++;
}
// ignore trailing spaces
if(input[i - 1] != ' ') {
// get last parsed integer
v *= num;
}
printf("%i\n", v);
return 0;
}

Program stops when i input any character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
*the code is from a book named
Programming with c by Byron gottfried *
*when i try to input a character, the program stops *
int main()
{
char line[80];
int count;
printf(" Enter a line of text below:\n");
scanf("%[^\n], &line");
for(count=0;line[count]!='\0';++count){
if(((line[count]>='0') && (line[count] < '9'))||
((line[count] >= 'A') && (line[count]< 'Z'))||
((line[count]>= 'a' ) && (line[count] <'z' )))
putchar(line[count]+1);
else if(line[count] =='9' ) putchar('0');
else if(line[count] == 'Z')putchar('A');
else if(line[count] == 'z')putchar('a');
else putchar('.');
}
return 0;
}
The line:
scanf("%[^\n], &line");
Should be:
scanf("%[^\n]", line);
i.e. Put the closing " in the format string in the correct place, and no & before line.
Moreover, on some platforms the stdout buffer is not flushed until it contains a newline or becomes full, so you should add a fflush( stdout) call. You will get away with it on Windows.
You might also consider simplifying the code by using the ctype.h functions.
Since this is a simple transcription error (the book referenced does not contain this error) rather than a programming question, and the question has been closed, this purely an aside, but I'd suggest the following implementation.
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[80];
int count;
/* read in the entire string */
printf("Enter a line of text below:\n");
scanf("%[^\n]", line);
/* encode each individual character and display it */
for (count = 0; line[count] != '\0'; ++count)
{
char plaintext = line[count];
char encoded = '.';
if (isupper(plaintext))
{
encoded = (((plaintext + 1) - 'A') % 26) + 'A';
}
else if (islower(plaintext))
{
encoded = (((plaintext + 1) - 'a') % 26) + 'a';
}
else if (isdigit(plaintext))
{
encoded = (((plaintext + 1) - '0') % 10) + '0';
}
putchar(encoded);
}
return 0;
}

Resources