#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
int main()
{
ifstream input("numbers.txt");
int a[500000];
if (input.is_open())
{
for (int i = 0; i <= 499999; i = i + 50000)
{
input >> a[i];
cout << a[i] << endl;
}
}
else
cout << "Could not open File" << endl << endl;
}
The file name "numbers.txt" is a simple txt file that contains exactly 500,000 integer numbers. Testing this code out on a small file of 100 integers it worked fine, but whenever I read this file is gave me the usual "file.exe has stopped working". Any idea why?
Related
I wrote a C++ code using iterative methods. For this, I used a FOR loop. However, I need to save every result by iteration in same text file (or DATA file) as a columns. How can I do it? Thanks for your advices.
This a simple version of my code:
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int i;
main()
{
cout<<"Value 1"<<right<<setw(20)<<"Value 2"<<endl;
for(i=0;i<5;i++)
{
cout<< left << setw(20) << i+10
<< setw(20) << i<<endl;
}
getch();
}
For most purposes using a CSV file would be better. Here is a code that does what you need.
#include <stdio.h>
int main() {
FILE * fpw; // A file pointer/handler that can refer to the file via a cpp variable
fpw = fopen("data.txt", "w"); // Open the file in write("w" mode
if (fpw == NULL) {
printf("Error"); // Detect if there were any errors
return 0;
}
fprintf(fpw, "Value 1,Value 2\n"); // Write the headers
int i = 0;
for (i = 0; i < 5; i++) {
fprintf(fpw, "%d,%d\n", i + 10, i); // Write the values
}
fclose(fpw); //Don't forget to close the handler/pointer
return 0;
}
Output:
A file data.txt will be created with following contents:
Value 1,Value 2
10,0
11,1
12,2
13,3
14,4
Here i have a while loop which is ment to have a condition to be satisfied, when i receive the whole message from My Arduino. The problem is that: i dont know how i could change this condition
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
i have inspired all my project from Here
but i have changed the main function and my arduino file. here is my main function:
//This code snippet will help you to read and write data from arduino
//#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "SerialClass.h"
#include <fstream>
//using namespace std;
using std::cin;
using std::cout;
using std::endl;
//String for getting the Output from Arduino
char outputData[MAX_DATA_LENGTH];
//String for incoming data
char incomingData[MAX_DATA_LENGTH];
//Portname must contain these backslashes
char *port_name = "\\\\.\\COM5";
const unsigned int bufSize =255;
int main()
{
SerialPort arduino(port_name);
if (arduino.isConnected())
std::cout << "Connection Established! \n" << std::endl;
else
std::cout << "ERROR, check port!";
while (arduino.isConnected()) {
std::string input_string ;
//cout << "Write something: \n";
getline(cin, input_string);
//Creating a c string
char *c_string = new char[input_string.size() + 1];
//copying the std::string to c string
std::copy(input_string.begin(), input_string.end(), c_string);
//Adding the delimeter
c_string[input_string.size()] = '\n';
//Writing string to arduino
arduino.writeSerialPort(c_string, MAX_DATA_LENGTH);
//Getting reply from arduino
arduino.readSerialPort(outputData, MAX_DATA_LENGTH);
//printing the output
//puts(outputData);
//freeing c_string memory
delete[] c_string;
//Check if data has been read or not
int read_result;
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
//wait a bit
//Sleep(100000);
}
}
and here is my arduino file:
int PButton=2;
int Led=13;
unsigned long start,finished,elapsed;
void setup() {
Serial.begin(9600); //begins the Serial Connection.
pinMode(PButton, INPUT_PULLUP);
pinMode(Led,OUTPUT);
digitalWrite(Led,LOW);
Serial.println("Is the video already started? ""yes/no""...\n");
start=millis();
String ans;
while(Serial.available()<=0)
{
}
ans=Serial.readStringUntil('\n');
if(ans.equals("yes")){
digitalWrite(13,HIGH);
Serial.println("The video is started!\n\nplease Press the Pushbutton when the task is fullfilled!\n");
}
else if(ans.equals("no")){
digitalWrite(13,LOW);
Serial.println("The Video is still not started! \n");
}
}
void loop() {
int buttonState=digitalRead(PButton); //read the input pin
if(buttonState==LOW)
{
Serial.print("The pushbutton is pressed after ");
finished=millis();
elapsed=finished-start;
Serial.println(elapsed);
delay(3000);
}
}
I'm trying to write a program that creates a structure for student info, has an array with 4 students info, writes the info to a text file, and returns the information back from the text file. I'm also supposed to do the same process with binary I/O, but that part works well so I took it out of the code. My issue is with the text file. I believe the issue is with the name part of the array. I also have the guideline to follow: "Do not use the string class in your struct definition. Instead, use the old c-style string (i.e. array of char)" I can't figure out how to get the program to step over the space between first/last names. This is the code I have written:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;
/* structure */
struct studentInfo
{
char name[40];
int age;
float gpa;
char grade;
};
int main(int argc, const char * argv[])
{
const int SIZE = 4;
int i;
/* array */
studentInfo student[SIZE]{ {"Ann Annson\0", 10, 1.10, 'D'},
{"Bill Billson\0", 20, 2.20, 'C'},
{"Carl Carlson\0", 30, 3.30, 'B'},
{"Don Donson\0", 40, 4.00, 'A'} };
/* open & write to file in text mode i/o */
fstream fFile;
fFile.open("students.txt", ios::out);
for(i = 0; i < SIZE; i++)
{
fFile << student[i].name << endl;
fFile << student[i].age << endl;
fFile << student[i].gpa << endl;
fFile << student[i].grade << endl;
}
fFile.close();
/* open and read information from files to new arrays */
studentInfo studentsText[4];
fFile.open("students.txt", ios::in);
for(i = 0; i < SIZE; i++)
{
fFile >> studentsText[i].name;
fFile >> studentsText[i].age;
fFile >> studentsText[i].gpa;
fFile >> studentsText[i].grade;
}
fFile.close();
/* display the information from students.txt */
cout << "This is the data contained in students.txt: " << endl;
for (i = 0; i < SIZE; i++)
{
cout << studentsText[i].name << "\t" << studentsText[i].age;
cout << "\t" << studentsText[i].gpa << "\t" << studentsText[i].grade << endl;
}
return 0;
}
this is the output that I receive when I run the program:
screenshot
and this is the output I'm trying to get:
screenshot
I do know that it is an issue regarding the space, because if I run the program with the spaces between the names in the array removed it returns this output: screenshot
Forgive me if this is a poor question, I'm in my first semester of c++ and I hope that I worded this well for anyone that attempts to help. Thank you to everyone who looks at this and tries to help!
side note
this is the full code I have written
and this is the output I receive when running that code
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
string checkpass(string password1)
{
string rightpass = "aimen";
string errormsg2;
if (password1 == rightpass)
{
errormsg2 = "Right";
}
else{errormsg2 = "No";}
return errormsg2;
}
int main()
{
string password;
string errormsg;
cout << "Type the password";
loop:
getline (cin,password);
errormsg == checkpass(password);
if (errormsg=="Right")
{
cout << "Admitted" << endl;
}
else {
goto loop;
}
system("pause");
return 0;
}
Console doesn't print the word "Admitted". It launches, but after my putting in the console words, repeatedly occur nothing.
I request your aid. Thank you.
You are comparing with errormsg == checkpass(password); when you should assign with one = symbol.
Good day. I could really use your help on this one. I have a stats text file in the following format.
ID=1000000
Name=Name1
Field1=Value1
...(Fields 2 to 25)
Field26=Value26
ID=1000001
Name=Name2
Field1=Value1
...(Fields 2 to 25)
Field26=Value26
ID=1000002
Name=Name2
Field1=Value1
...(Fields 2 to 25)
Field26=Value26
...goes up to 15000
I have an active people text file separated by line breaks.
Name2
Name5
Name11
Name12
...goes up to 1400 Random Names
I need to be able to delete records from the stats text file (ID, Name, Fields1 to 26) if the name is not found in the active people text file. In the example above, the associated record for Name1(ID, Name, Fields1 to 26) should be deleted since it's not in the active people text file.
I've tried reformatting the stats file through notepad++ using TextFX->Quick->Find/Replace to convert it to a comma separated file with each record separated by a line break. I had it rearranged to
ID Name Field1 ...Fields2 to Fields 25... Field26
1000000 Name1 Value1 ...Value2 to Value 25... Value26
1000001 Name2 Value1 ...Value2 to Value 25... Value26
1000002 Name2 Value1 ...Value2 to Value 25... Value26
I've opened it with excel and I've created two tables (stats table and a active names table) in mysql using the csv file file. I'm not sure how to process this in an automatic function. Besides removing inactive records, the other problem I have is rewriting it back to its old format.
I've been trying my best to figure this out for a hours on end. Is there a solution that won't require me to use find, copy, paste and switch between the two files 1400 times? Unfortunately, I have to keep the stats file in this format.
Please help. Thank you.
Here's a C++ program that will process the files for you:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <locale>
#include <set>
#include <string>
#include <vector>
//trim functions taken:
//http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring/217605#217605
//with a slight change because of trouble with ambiguity
static int myIsSpace(int test)
{
static std::locale loc;
return std::isspace(test,loc);
}
static std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(myIsSpace))).base(), s.end());
return s;
}
static std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(myIsSpace))));
return s;
}
static std::string &trim(std::string &s) {return ltrim(rtrim(s));}
int main(int argc,char * argv[])
{
std::ifstream peopleFile;
peopleFile.open("people.txt");
if (!peopleFile.is_open()) {
std::cout << "Could not open people.txt" << std::endl;
return -1;
}
std::set<std::string> people;
while (!peopleFile.eof()) {
std::string somePerson;
std::getline(peopleFile,somePerson);
trim(somePerson);
if (!somePerson.empty()) {
people.insert(somePerson);
}
}
peopleFile.close();
std::ifstream statsFile;
statsFile.open("stats.txt");
if (!statsFile.is_open()) {
std::cout << "could not open stats.txt" << std::endl;
return -2;
}
std::ofstream newStats;
newStats.open("new_stats.txt");
if (!newStats.is_open()) {
std::cout << "could not open new_stats.txt" << std::endl;
statsFile.close();
return -3;
}
size_t totalRecords=0;
size_t includedRecords=0;
bool firstRecord=true;
bool included=false;
std::vector<std::string> record;
while (!statsFile.eof()) {
std::string recordLine;
getline(statsFile,recordLine);
std::string trimmedRecordLine(recordLine);
trim(trimmedRecordLine);
if (trimmedRecordLine.empty()) {
if (!record.empty()) {
++totalRecords;
if (included) {
++includedRecords;
if (firstRecord) {
firstRecord=false;
} else {
newStats << std::endl;
}
for (std::vector<std::string>::iterator i=record.begin();i!=record.end();++i) {
newStats << *i << std::endl;
}
included=false;
}
record.clear();
}
} else {
record.push_back(recordLine);
if (!included) {
if (0==trimmedRecordLine.compare(0,4,"Name")) {
trimmedRecordLine=trimmedRecordLine.substr(4);
ltrim(trimmedRecordLine);
if (!trimmedRecordLine.empty() && '='==trimmedRecordLine[0]) {
trimmedRecordLine=trimmedRecordLine.substr(1);
ltrim(trimmedRecordLine);
included=people.end()!=people.find(trimmedRecordLine);
}
}
}
}
}
if (!record.empty()) {
++totalRecords;
if (included) {
++includedRecords;
if (firstRecord) {
firstRecord=false;
} else {
newStats << std::endl;
}
for (std::vector<std::string>::iterator i=record.begin();i!=record.end();++i) {
newStats << *i << std::endl;
}
included=false;
}
record.clear();
}
statsFile.close();
newStats.close();
std::cout << "Wrote new_stats.txt with " << includedRecords << " of the " << totalRecords << ((1==totalRecords)?" record":" records") << "found in stats.txt after filtering against the " << people.size() << ((1==people.size())?" person":" people") << " found in people.txt" << std::endl;
return 0;
}