I wrote some program which overwrites some text in .txt file and put the overwritten one in another output.txt... But it's constantly saying that the file can't be opened. What should I do?
#include <stdio.h>
#include <ctype.h>
int main()
{
FILE *ul=fopen("hexbr.txt","r"),*iz=fopen("bitovi.txt","w");
int i;
char ch;
if ((!ul)||(!iz)) { printf("Neuspesno otvaranje datoteke!");return 0; }
while((ch=fgetc(ul))!=EOF)
{
if ((isdigit(ch)) || (c>='A' && c<='F'))
{
if (isalpha(ch))
switch(ch)
{
case 'A': { fputc('1',iz);fputc('0',iz);fputc('1',iz);fputc('0',iz);continue; }
case 'B': { fputc('1',iz);fputc('0',iz);fputc('1',iz);fputc('1',iz);continue; }
case 'C': { fputc('1',iz);fputc('1',iz);fputc('0',iz);fputc('0',iz);continue; }
case 'D': { fputc('1',iz);fputc('1',iz);fputc('0',iz);fputc('1',iz);continue; }
case 'E': { fputc('1',iz);fputc('1',iz);fputc('1',iz);fputc('0',iz);continue; }
case 'F': { fputc('1',iz);fputc('1',iz);fputc('1',iz);fputc('1',iz);continue; }
}
for(i=0;i<4;i++)
{
fputc((ch & 0X8)?'1':'0',iz);
ch<<=1;
}
}
else fputc(ch,iz);
if (ch=='\n') { ch=fgetc(ul);fputc(ch,iz); }
}
fclose(ul);
fclose(iz);
return 0;
}
The program did not compile without error, there is a pair of typos here, c should be ch:
... (c>='A' && c<='F') ...
Apart from that the program almost works, and the output file (created in the same folder as the executable) is readable.
There is a mistake in trying to handle newline chars, which mistakenly causes the next (printing) char to be passed through and not converted to binary. I left newline and return to be passed through like other non-hex chars.
Other than that, the handling of A..F is clumsy. I suggest trapping them like this:
while((ch=fgetc(ul))!=EOF)
{
if ((isdigit(ch)) || (ch>='A' && ch<='F'))
{
if (isalpha(ch))
ch -= 7;
for(i=0;i<4;i++)
{
fputc((ch & 0X8)?'1':'0',iz);
ch<<=1;
}
}
else fputc(ch,iz);
}
And you might want to check and convert the lower case a..f too.
Related
I am attempting to parse a command line argument, which in turn will execute an associated case within a switch statement. When I parse an integer argument (as seen in the code below), the associated case executes correctly. When I attempt to parse a string such as "CPU", I do not get the correct output.
Functioning code (parsing an integer e.g. an argument of 4 gives athe correct output of hello):
#include <stdio.h>
int main(int argc, char *argv[]) {
char execution_mode = atoi (argv[1]);
switch (execution_mode)
{
case (4) :
printf("Hello");
getchar();
break;
case (8) :
printf("Goodbye");
getchar();
break;
default:
printf("Error! execution mode is not correct");
getchar();
break;
}
return 0;
}
My attempt at parsing a string e.g. the argumentCPU:
#include <stdio.h>
int main(int argc, char *argv[]) {
typedef enum MODE { CPU, OPENMP } MODE;
MODE execution_mode = (char)argv[1];
switch (execution_mode)
{
case (CPU) :
printf("Hello");
getchar();
break;
case (OPENMP) :
printf("Goodbye");
getchar();
break;
default:
printf("Error! execution mode is not correct");
getchar();
break;
}
return 0;
}
You cannot convert a string to an enumerate like this. What you're doing is just converting the pointer to the string to char. Which fails.
One alternative (besides comparing first argument with strcmp) to avoid this would be to give a character value to your enumerates:
typedef enum { CPU='C', OPENMP='O' } MODE;
and now you can pick the first letter of the first argument and convert it:
MODE execution_mode = (MODE)argv[1][0];
The letters must be of course all different. And check argc>1 to see if argv[1] is valid, of course
If you want full string match, you have no other choice than using strcmp:
const char *execution_mode = argv[1];
if (strcmp(execution_mode,"CPU")==0)
{
// do something
}
else if (strcmp(execution_mode,"OPENMP")==0)
{
// do something else
}
With the help of the users who have answered this question, I have found a working solution by using strcmp as seen below. I have also added some error checking to ensure enough arguments have been enterred on the command-line.
#include <stdio.h>
int main(int argc, char *argv[]) {
//Ensure there are enough arguments
if (argc < 2)
{
printf("Error: not enough arguments");
exit(1);
}
typedef enum MODE { CPU, OPENMP, CUDA, ALL } MODE;
MODE execution_mode = (MODE)argv[1];
//Compare string with command-line arguments
if (strcmp("CPU", execution_mode) == 0)
{
//selects CPU case
execution_mode = CPU;
}
else if (strcmp("OPENMP", execution_mode) == 0)
{
//selects OPENMP case
execution_mode = OPENMP;
}
else
{
printf("invalid arg");
}
//Switch statement
switch (execution_mode)
{
case (CPU) :
printf("CPU MODE SELECTED");
getchar();
break;
case (OPENMP) :
printf("OPENMP MODE SELECTED");
getchar();
break;
default:
printf("Error: execution mode is not correct");
getchar();
break;
}
return 0;
}
The program needs to execute until 'q' is pressed. But the below code what I wrote it is only executing whichever case is first and then stops executing further cases. Ex: case 1.if my input is p, q, then only p case is executed, not the q.
case 2.if my input is g, q, then only g case is executed, not the q.
int main()
{
int i,n,cnt;
char value[10]={0,0,0,0,0,0,0,0,0,0};
int index; float values,Max;
int *val;
bool quit=false;
float num[10]={1.500, 2.200, 7.300, 9.200, 7.400, 7.500, -8.000, 1.500, 12.000, 0.000};
for(i=0;i<20;i++)
{
scanf("%c",&value[i]);
if(value[i]=='r')
{
scanf("%d", &index);
scanf(", %3f",&values);
}
if((value[i] =='p')|(value[i] =='q')|(value[i] =='r')|(value[i] =='g')|(value[i] =='s'))
{
cnt++;
}
}
for(i=0;i<cnt;i++)
{
while(!quit)
{
switch(value[i])
{
//printf("Command (p/g/r/s/q):");
case 'p':
{
printf("Command (p/g/r/s/q):");
printValues(&num,10);
return;
}
case 'g':
{
printf("Command (p/g/r/s/q):");
Max= largestElement(&num,10);
printf("Max=%0.3f",Max);
return;
}
case 'r':
{
printf("Command (p/g/r/s/q):");
replaceElement(&num,index,values);
printValues(&num,10);
return;
}
case 's':
{
printf("Command (p/g/r/s/q):");
sortOnValue(&num,10);
printValues(&num,10);
return;
}
case'q':
{
printf("Command (p/g/r/s/q):");
quit= true;
break;
}
default:
{
printf("help");
return;
}
}
}
}
return 0;
}
Within most of your case blocks you probably want break rather than return to exit the switch. At the moment you are returning frommain() and consequently exiting the program. break transfers control to the end of the switch and your program can then continue.
The case 'q' block would then have a return to exit the program.
Few problems here.
for(i=0;i<20;i++) you are accessing out of bound so your loop should be
for(i=0;i<10;i++).
You need to add ' ' in the format string to consume new line character (\n).
`scanf(" %c",&value[i]);`
You are using | operator instead of || hence your if should be.
if((value[i] =='p')||(value[i] =='q')||(value[i] =='r')||(value[i] =='g')||(value[i] =='s'))
{
cnt++;
}
You are using return instead of break in your switch case.
change this
case 'p':
{
printf("Command (p/g/r/s/q):");
printValues(&num,10);
return;
}
to
case 'p':
{
printf("Command (p/g/r/s/q):");
printValues(&num,10);
break;
}
Your while(!quit) inside the for loop is not useful and will lead to infinate loop when used break statement inside switch case. Hence remove the while(!quit) and change your for loop as below.
for(i=0;i<cnt&&!quit;i++)
side note:: It is high time for you
learn-how-to-debug-small-programs
I am writing a code which compares two strings for a simple guessing game. One string is pre-set, in my code it's "Eggman", and this is then compared with a user input, if the letter in the same position is the same then the user is shown the letter on screen, if it is not the same as the pre-set string then a question mark appears. For example, since the pre-set string is "Eggman" the user will be asked for an input, if the input is for example "Eclair", then the program outputs "E?????", which is exactly what I want the program to do, however, I have used multiple if statements, which has made the code inconvenient, and cannot really think of a way to do it with iteration. I thought about using the strcmp() function, but I pretty sure that it can't be used to compare singular characters in a string. The code is below:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void checkAnswer();
int main()
{
checkAnswer();
return 0;
}
void checkAnswer()
{
char word[]="Eggman";
char input[4096];
printf("Guess the word:");
scanf("%s", input);
if (word[0]==input[0])
{
printf("E");
}
else
{
printf("?");
}
if (word[1]==input[1])
{
printf("g");
}
else
{
printf("?");
}
if (word[2]==input[2])
{
printf("g");
}
else
{
printf("?");
}
if (word[3]==input[3])
{
printf("m");
}
else
{
printf("?");
}
if (word[4]==input[4])
{
printf("a");
}
else
{
printf("?");
}
if (word[5]==input[5])
{
printf("n");
}
else
{
printf("?");
}
}
As you asked there is much easier way to solve your problem instead of definend multiple if else you can use loop.
I have tried to solve your problem, hope it will help:
#include<stdio.h>
int main()
{
char word[]="Eggman";
char input[4096];
char abc[] ={0};
int i=0,f=0;
printf("Guess the word:");
scanf("%s", input);
while(1){
if(strcmp(input,word)==0)
{
break;
}
else
{
if(f==1){
scanf("%s", input);
}
else
{
f=1;
}
}
for(i=0;i<strlen(word);i++)
{
if(input[i]==word[i])
{
printf("%c",input[i]);
}
else
{
printf("?");
}
}
}
}
The above program will ask your again and again till the user input matched with the declared string.
While making a asteroid shooter, I came around using _kbhit() and kbhit(). I'm no expert, but here is the problem I think I'm having:
int run = 1;
int main() {
while(run){
if(GetUserInput() == 2)
printf("W");
if(GetUserInput() == 1)
printf("S");
Sleep(50);
}
}
int GetUserInput(){
if(kbhit()){
char c = _getch();
if(c == 's')
return 2;
if(c == 'w')
return 1;
}
else
return 0;*
}
So, what I think is happening, it does the first check on GetUserInput(), and because of the nature of getch(), the keyboard is read from the buffer and discarded? Anyways, I store the value in c and should return appropriately. But it only does the first check. Is it because there is no more input on the buffer after the first check (in the main() function)?
Your problem is that you're trying to read once for every key you're interested in with this code:
if(GetUserInput() == 2)
printf("W");
if(GetUserInput() == 1)
printf("S");
For example, I press 'S', you read the key, check if the return value is 2 and it is not. Then you try to read another key, but I haven't pressed one, so the second check for 'S' also fails.
To fix this you need to perform all of your tests on the value you get from GetUserInput().
int val = GetUserInput();
if(val == 2)
printf("W");
else if(val == 1)
printf("S");
You don't need to use else if, but once you've found a match it makes no sense to keep checking if all of your checks are mutually exclusive. You might consider using a switch statement and an enum instead of hardcoded magic values, or even return the key value directly if one is pressed and a sentinel value like 0 that won't match any of the keys you're interested in.
Here is a complete example that works for me:
#include <conio.h>
#include <stdio.h>
int GetUserInput()
{
if (_kbhit())
{
char c = _getch();
switch (c)
{
case 's':
case 'S':
return 2;
case 'w':
case 'W':
return 1;
case 'x':
case 'X':
return -1;
}
}
return 0;
}
int main()
{
for (;;)
{
int c = GetUserInput();
switch (c)
{
case 1:
printf("W");
break;
case 2:
printf("S");
break;
case -1:
return 0;
}
}
return 0;
}
I'm using ncurses and I'm getting input string with getstr(). I want to make something like autocompletion by Tab keystroke. However, I don't see a way to catch Tab with getstr(). I tried this:
char input = 0;
while (input != '\n')
switch (input = getch())
{
case '\t':
printw("Got Tab\n");
break;
default:
addch(input);
break;
}
But in this case I have to write my own handlings for Backspace, Delete etc., what is undesirable and essentialy is reinventing of wheel.
Maybe try:
switch (input = getch())
{
case KEY_STAB:
printw("Got Tab\n");
break;
default:
addch(input);
break;
}
Complete list of keys
This one works fine for me:
#include <cstdio>
#include <conio.h>
int main() {
char input = 0;
while (input != '\n') {
input = getch();
switch (input)
{
case '\t':
printf("T");
break;
case '\b':
printf("\b \b");
break;
default:
printf("%c", input);
break;
}
}
}
using the latest g++