Program stops when i input any character [closed] - c

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;
}

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++;
}
}

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;
}

I've got an issue with my Enigma simulation [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 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';
}

Converting an array of letter to an array of numbers [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 8 years ago.
Improve this question
I have a text file in D drive named "data.txt". It has several columns and rows like:
A B A B V B
B V A B A A
B B A A B A
I want to read the "program.txt" file and then convert it to numbers say A=1, B=2, V=3 and then write it so that it will be a array of number. But I'm not sure where to begin. Can someone point me in the right direction?
#include <stdio.h>
int main() {
int n,k;
char C;
FILE *fptr;
fptr=fopen("D:\\program.txt","r+");
printf("Enter n: ");
scanf("%d",&n);
if (n == C){
fprintf(fptr,"%d",3);
}
fclose(fptr);
return 0;
}
From your question, it looks like you want to assign a new number to each character as you encounter it. So you need to keep track of what you've seen and what number was assigned, as well as the current number.
You can do this with an array:
int values[256] = {0};
int next_value = 1;
When you read a character, you can check if you've already seen it. You may also want to check that it's in the right range. If you haven't seen it, assign a number. Otherwise use the number that was originally assigned:
if (c >= 'A' && c <= 'Z') {
if (!values[c]) values[c] = next_value++;
printf ("%d", values[c]);
}
Then it's just a matter of reading the file. There are many ways to do this, but I think the simplest in this case is to read each character from the file in a loop and output them after translating the ones you're interested in:
int c;
while (EOF != (c = getc(fp))) {
if (c >= 'A' && c <= 'Z') {
if (!values[c]) values[c] = next_value++;
printf ("%d", values[c]);
} else {
putchar(c);
}
}
#include <stdio.h>
int main() {
char line_buff[16];
FILE *fptr;
fpos_t pos;
fptr=fopen("D:\\program.txt","r+");
fgetpos(fptr, &pos);
while(fgets(line_buff, sizeof(line_buff), fptr)){//read one line
char *p = line_buff;
while(*p){//convert
if(*p == 'A')
*p++ = '1';
else if(*p == 'B')
*p++ = '2';
else if(*p == 'V')
*p++ = '3';
else
++p;
}
fsetpos(fptr, &pos);
fprintf(fptr, "%s", line_buff);//rewrite
fflush(fptr);
fgetpos(fptr, &pos);//memo position
}
fclose(fptr);
return 0;
}

Resources