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;
}
Related
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++;
}
}
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 4 years ago.
Improve this question
As a part of an assignment I've got, I need to get from a user a digit only using the <stdio.h> library.
do {
scanf("%d",&num);
} while (num>9 || num<0);
But the program will get from the user also chars and other things.
Any advice?
One way of solving this is getting the ASCII value of the scanned "digit" and making sure it lies between ASCII values 0X30 and 0X39 (or 48 and 57).
Seeing your logic, you seem to be interested in numbers greater than 9 (multiple digit numbers) and numbers less than 0 (signed numbers/integers).
I suggest instead of using scanf better use something like getchar which will return one character at a time.
A simple way to scan multiple digit numbers using getchar can be:
int getNumber()
{
int sign = 1;
int i = 0;
int ch;
ch = getchar();
if((ch == '-') || (ch == '+')) //check sign
{
if(ch == '-') sign = -1;
}
else
{
if (ch > '9' || ch < '0')
return NULL; // Your requirement - it's a non number
i *= 10;
i += ch - '0';
}
while ((ch = getchar()) != '\n') //get remaining chars
{
if (ch > '9' || ch < '0')
return NULL; // Your requirement - it's a non number
i *= 10;
i += ch - '0';
}
i *= sign; //change sign
return i;
}
You can call this function in place of scanf.
You can use getchar() to read a single character from stdin and then compare it to the ASCII values for 0 and 9 (your upper and lower bounds for a single character). The digit as an integer is equal to the character code minus the character code for 0.
#include <stdio.h>
int main(void) {
char c;
while((c = getchar()) >= '0' && c <= '9')
printf("Digit is: %d\n", c - '0');
return 0;
}
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
I have a file named myf which has a lot of text in it and I am trying to use blank spaces as a way of counting the number of words. Basically, in the count method of my program, there is a variable int d which acts like a boolean function. Also, there is an incrementer called count.
I have a for loop which will traverse the array that's put into the argument of the method count, and will see if the pointer *p is a non letter. If it is a non letter AND d=0, d=1 and count is incremented. This way, if the next character is also a non space, since d=1, the else if statement will not be incremented again. The only way for d to reset to 0 is if a space is present, at which point, if another letter is found, it will be incremented again. Then the method count will return the variable count. Seems simple enough, but I keep getting wrong numbers.
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
int count(char x[]) {
int d = 0;
int count = 0;
for (char *p = x; *p != EOF; *p++) {
// this will traverse file
printf("%c", *p);
// this is just to see the output of the file
if (*p == ' ' && d == 1) {
d = 0;
}
else if (*p != ' ' && d == 0) {
count++;
d = 1;
}
}
return count;
}
int main() {
char c;
int r = 0;
char l[1000];
FILE *fp = fopen("myf", "r");
while ((c = fgetc(fp)) != EOF) {
l[r] = c;
r++;
}
printf("\n %d", count(l));
}
To count the number of words, count the occurrences of a letter after a non-letter.
*p != EOF is the wrong test. EOF indicate that the input operation either 1) had not more input or 2) an input error occurred. It does not signify the end of a string.
Use int to save the result from fgetc() as that returns an int in the range of unsigned char and EOF. Typically 257 different values. char is insufficient.
Small stuff: No need for an array. Let code consider ' as a letter. As the number of words could be very large, let code use a wide type like unsigned long long.
#include <ctype.h>
int isletter(int ch) {
return isalpha(c) || c == '\'';
}
#include <stdio.h>
int main(void) {
unsigned long long count = 0;
FILE *fp = fopen("myf", "r");
if (fp) {
int c;
int previous = ' ';
while ((c = fgetc(fp)) != EOF) {
if (!isletter(previous) && isletter(ch)) count++;
previous = ch;
}
fclose(fp);
}
printf("%llu\n", count);
}
Don't do this
*p != EOF
EOF is actually a negative integer and you're using it as a char. You should pass in how many character you want to iterate over ie
int count(char x[], int max){
then use the for loop like
int m = 0;
for ( char *p = x; m < max; p++, m++)
Note I also changed *p++ to p++. You also need to update your program to consider things that are non space etc ie this line
else if (*p != ' ' && d==0 )
What happens when it encounters a \n, it will likely count an extra word.
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;
}
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 9 years ago.
Improve this question
I'd like to ask you about my prog. The main purpose of this one is to fill the "result" array with data collect from "tab1" and "tab2" arrays. Could anybody check, why does results are so weird? Thank you.
#include <stdio.h>
#include <stdlib.h>
void laczenie(char tab1[],char tab2[])
{
int i;
char* result =(char*) malloc(100*sizeof(char));
for(i=0;i<30;i++)
{
if(tab1[i] != '\0') tab1[i]==result[i];
else if (tab2[i] !='\0')tab2[i]==result[i];
else printf(" ");
}
for(i=0;i<30;i++)printf("%c",result[i]);
free(result);
}
int main()
{
char x[10]={'n','a','p','i','s','1'};
char y[10]={'n','a','p','i','s','2'};
//char x[10] = {"napis1"};
//char y[10] = {"napis2"};
laczenie(x,y);
return 0;}
In addition to LihOs answer above this block looks wrong:
if(tab1[i] != '\0')
tab1[i]==result[i];
else if (tab2[i] !='\0')
tab2[i]==result[i];
else printf(" ");
Don't you mean to assign the value in tab1[i]or tab2[i] to result[i]like this?
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");
Also using magic numbers like in the loops: for(i=0;i<30;i++) is pretty bad practice, you should probably be using a constant for the size value (which you could then use in both the loops and in the array declarations. And why loop to 30 when the arrays is 10 elements only?
In your function you check for null-terminating character:
if(tab1[i] != '\0')
but where is null-terminating character here?
char x[10]={'n','a','p','i','s','1'};
Try:
char x[7]={'n','a','p','i','s','1','\0'};
Also note that tab1[i]==result[i]; compares tab[1] with result[i], if you want to assign the result[i] to tab1[i], use assignment operator =:
tab1[i]=result[i];
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");`
This is still wrong as by the time you assign tab2 to result i will be already at 6 so you will have to use two for loops i suppose for assign tab1 and tab 2