How can I write output to text file in C++ by script - c++

I written a code to create two random number with a given range. I want to write the output result (two random numbers). In script file, I want to write the output in same line for each iteration as my expected result
My current output is
1 0
1 0
2 1
2 3
0 0 //output of second iteration
1 1
2 2
1 3
My expected result is
1 0 0 0
1 0 1 1
2 1 2 2
2 3 1 3
This is my full code
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <time.h> /* time */
#define random(x) (rand()%x)
int main(int argc, char **argv) {
unsigned int time_ui = static_cast<unsigned int>( time(NULL) );
srand( time_ui );
int number1;
int number2;
int range=atoi(argv[1]);
number1 = random(range);
number2 = random(range);
//std::cout<< number1 << "\t" <<number2;
std::ofstream myfile;
myfile.open ("report.txt", std::ios::app);
myfile << number1 << "\t" <<number2<<'\n';
myfile.close();
return 0;
}
My script file is
#!/bin/bash
a=1
iter=0
for ((iter; iter <= 1; iter++))
do
a=1
while [ $a -lt 4]
do
./random_num $a
a=`expr $a + 1`
done
done

Note that there is a newline character that you output in your C++ code, which makes it nearly impossible to "unoutput". I would suggest moving the logic from the bash into the C++ code or vice versa. C++ has options such has setfill which can help you control this.

Related

Why do I get this error when I paste text into the Clion Run window?

I'm testing a simple program via Clion 2022.2.4.
#include<iostream>
int main() {
int n, num[10] = {0};
std::cin >> n;
for (int i = 1; i <= n; i++)
std::cin >> num[i];
for (int i = 1; i <= n; i++)
std::cout << num[i] << " ";
return 0;
}
When I paste the following into the Run window via the clipboard and hit Enter, it turns out as expected.
Input:
4
1 2 2 2
Output:
1 2 2 2
When I pasted the following into the Run window via the clipboard, hit the backspace key, typed 2, and then hit enter, the result changed.
Input:
4
1 2 2 2
Output:
1 2 2 24
We can see that the last number changes from 2 to 24. But in fact the input for both operations before and after is 4 1 2 2 2 2(At least that's what it looks like).
Meanwhile, I tried some other inputs
By typing 4 1 2 2 1 through the clipboard, then change the last 1 to 8, the output is as follows:
Input:
4
1 2 2 8
Output:
1 2 2 14
By typing 3 1 2 3 through the clipboard, then change the last 3 to 7, the output is as follows:
Input:
3
1 2 3
Output:
1 2 33
I noticed that it seems that the last anomalous number is a combination of the last number on the clipboard and n.
Also, if n is entered on the same line as another n numbers, the result is correct even if the last number is modified.
Input:
4 1 2 2 2
Output:
1 2 2 2
So I want to know what's going on here, or is this just a bug?
I am not sure what is the issue you are having with the processing of terminal input.
Nevertheless there are several issues in your code:
Array indices are 0..n-1 (not 1..n) - where n is the number of elements.
In c++ is is better to use std::vector instead of c style arrays
(or std::array for fixed size and usually small arrays).
Using std::vector will make your code support an arbitrary array size (not bound by e.g. 10 like in your code).
As mentioned in the comments above, it is recomended to end the output with a newline to avoid having the terminal prompt on the same line.
Better version:
#include <iostream>
#include <vector>
int main() {
int n;
std::vector<int> num;
std::cin >> n;
num.resize(n);
for (int i = 0; i < n; ++i)
std::cin >> num[i];
for (int i = 0; i < n; ++i)
std::cout << num[i] << " ";
std::cout << std::endl;
return 0;
}

convert an array string to intger c++ (beginner)

I have a text file which that contains only numbers inside , and i have successfully pulled the numbers from the file and stored it inside an array:
my problem is that the array is "string" and i cant do mathematical operations on the array like Addition and Subtraction
I have tried to use atoi(array[i][j].c_str()) to convert it to intger
but it gives me only the first digit of a number!
my program looks like this for now , its a mess I know :(
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
ifstream iFile("input.txt");
string line;
string array[7][7];
for (int i=0;i<7;i++){
for (int j=0;j<6;j++){
getline(iFile,line);
if (!line.empty()){
array[i][j]=line;
}
else {
break;
}
}
}
cout<<"number of processes is: "<<array[0][0]<<endl;
cout<<"resource types: "<<array[1][0]<<endl<<endl;
cout<<"Allocation Matrix:"<<endl;
cout<<" A B C D"<<endl;
cout<<"0: "<<array[2][0]<<endl;
cout<<"1: "<<array[2][1]<<endl;
cout<<"2: "<<array[2][2]<<endl;
cout<<"3: "<<array[2][3]<<endl;
cout<<"4: "<<array[2][4]<<endl;
cout<<"Max Matrix:"<<endl;
cout<<" A B C D"<<endl;
cout<<"0: "<<array[3][0]<<endl;
cout<<"1: "<<array[3][1]<<endl;
cout<<"2: "<<array[3][2]<<endl;
cout<<"3: "<<array[3][3]<<endl;
cout<<"4: "<<array[3][4]<<endl;
cout<<"Need Matrix:"<<endl;
cout<<" A B C D"<<endl;
//cout<<"0: "<<array[3][1]+array[2][1]<<endl;
//int c= atoi(array[3][1].c_str());
//int c2= atoi(array[3][1].c_str());
//cout<<c+c2<<endl;
return 0;
}
my input.txt file looks like this:
5
4
0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4
0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6
1 5 2 0
1:0 4 2 0
edit:
note:if there is an empty line >> stop!
the program is based on banker algorithm which takes the first number from the input.txt as the numbers of of processes
then takes the second number as the numbers of of resource types
then takes the next numbers that there is no empty line between them as Allocation Matrix
then takes the next numbers that there is no empty line between them as max Matrix
and here is my problem when i want do Subtraction between Allocation Matrix and max Matrix because both are strings !
as for 1:0 4 2 0 it means do some operations with process number 1
You can use atoi but in c++ you have better options.
in c++ you can easily use stringstream to convert these types.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int convert_str_to_int(const string& str) {
int val;
stringstream ss;
ss << str;
ss >> val;
return val;
}
int main () {
string str = "1024";
int val = convert_str_to_int(str);
cout << "Val is: " << val << ", val/2 is " << val/2 << endl;
}

Searching words in a file with C++ language

I'm editing my post with the progress I made so far. Well, what I want to do for now is:
Read the text file from the first line without asterics (*), aka the line beginning with number 1, to the end of the file
When there is a "blank space" instead of ">sa0" (6th column) put a # on the variable. And put the next string on the next variable (aka fsa1)
Print this to the user line by line.
The code I have so far:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string line, netlist;
int address, fout, fin;
string name, type, fsa0, fsa1;
cout << "Wich Netlist you want to use?" << endl;
cin >> netlist;
ifstream file(netlist.c_str());
if (file.is_open())
{
do{
getline(file, line);
} while ( line[0] == '*' );
file >> address >> name >> type >> fout >> fin >> fsa0;
if (fsa0 != ">sa0") { fsa1 = fsa0; fsa0 = "#"; } else { file >> fsa1; }
cout << address << " " << name << " " << type << " " << fout << " " << fin << " " << fsa0 << " " << fsa1 << endl;
} else { cout << "File not found" << endl; }
file.close();
return 0;
}
Problems Found:
Not showing the first line after the last line with astherisc.
Not showing all the lines just the second one.
Text File im trying to read:
*c17 iscas example (to test conversion program only)
*---------------------------------------------------
*
*
* total number of lines in the netlist .............. 17
* simplistically reduced equivalent fault set size = 22
* lines from primary input gates ....... 5
* lines from primary output gates ....... 2
* lines from interior gate outputs ...... 4
* lines from ** 3 ** fanout stems ... 6
*
* avg_fanin = 2.00, max_fanin = 2
* avg_fanout = 2.00, max_fanout = 2
*
*
*
*
*
1 1gat inpt 1 0 >sa1
2 2gat inpt 1 0 >sa1
3 3gat inpt 2 0 >sa0 >sa1
8 8fan from 3gat >sa1
9 9fan from 3gat >sa1
6 6gat inpt 1 0 >sa1
7 7gat inpt 1 0 >sa1
10 10gat nand 1 2 >sa1
1 8
11 11gat nand 2 2 >sa0 >sa1
9 6
14 14fan from 11gat >sa1
15 15fan from 11gat >sa1
16 16gat nand 2 2 >sa0 >sa1
2 14
20 20fan from 16gat >sa1
21 21fan from 16gat >sa1
19 19gat nand 1 2 >sa1
15 7
22 22gat nand 0 2 >sa0 >sa1
10 20
23 23gat nand 0 2 >sa0 >sa1
21 19
And, another thing, can you guys give me some tips on what to do with these lines only with two integers, like the last one?
Thank you all. I appreciate all the help.
At least IMO, you're approaching this the wrong way. I'd start by reading a line of input. Then check how many items there are on that line. Then parse the items in the line appropriately.
Unless you're absolutely set on doing this in pure C++ on your own, something like AWK or yacc will make the job tremendously easier.
If you do insist on doing it without a parser generator or similar, you could at least use regular expressions to help out quite a bit.

How to read from a file [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 9 years ago.
* For those having this problem, it was the problem with my command. Make sure your command to compile and run the program is correct!
I was watching a tutorial on youtube.
I did exactly the same as the op did, and I get a different output.
I am new to c++, and I am using Xcode to run the code.
here is the code: (again, it's not mine, but from a youtube tutorial video)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int input[100];
int x = 0;
int fail = 0;
int pass = 0;
fstream textfile;
textfile.open("exam.txt");
while(! textfile.eof()) {
textfile >> input[x];
cout << input[x] << endl;
if(input[x] < 50) {
fail++;
}
else {
pass++;
}
x++;
}
textfile.close();
cout << fail << "students out of " << (fail + pass) << "did not pass the exam." << endl;
return 0;}
It's supposed to print grades.
But this is what I get when I run it on Xcode.
0
0
0
0
0
0
0
0
1606415288
32767
1606415720
32767
1606415720
32767
2003953588
1294056514
104
1
1606415312
32767
25240
1
1606415288
32767
1606415312
32767
25248
1
1606415288
32767
1606415312
32767
1606415720
32767
25264
1
1606415304
32767
1606415720
32767
1606415720
32767
6144
1
1910210376
32767
1606416728
32767
0
0
0
0
0
0
0
0
0
0
1606416544
32767
2003953588
1294056514
1606416544
32767
-1988827167
32767
0
0
1
0
1606416904
32767
0
0
It's only part of the output. It doesn't terminate.
Also, when I try to run it on linux (sshed into school linux machine),
I get this following error:
##?!#8 # #####?88#8###?? ??`?`?? ``?TT#T#DDP?tdPP#P#DDQ?tR?td??`?` /lib64/ld-linux-x86-64.so.2GNUGNU?Yd?`˫sP???*??"b!!?? (E?L?
CyIk? ^Q#y??K#??'?[?
#3P
# `??
#libstdc++.so.6__gmon_start___Jv_RegisterClasses_ZNSt8ios_base4InitD1Ev_ZNSt13basic_fstreamIcSt11char_traitsIcEEC1Ev_ZNSt13basic_fstreamIcSt11char_traitsIcEE5closeEv_ZNSirsERi_ZNSt13basic_fstreamIcSt11char_traitsIcEE4openEPKcSt13_Ios_Openmode__gxx_personality_v0_ZSt4cout_ZNSolsEi_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6__ZNSt13basic_fstreamIcSt11char_traitsIcEED1Ev_ZNSolsEPFRSoS_E_ZNKSt9basic_iosIcSt11char_traitsIcEE3eofEv_ZNSt8ios_base4InitC1Evlibgcc_s.so.1_Unwind_Resumelibc.so.6__stack_chk_fail__cxa_atexit__libc_start_mainGCC_3.0GLIBC_2.4GLIBC_2.2.5CXXABI_1.3GLIBCXX_3.4 P&y
xui ?ӯk?t)??`? ` ` ` ` `( `0 8 ` # ` p60ii
H `
P `
` `h `p `x `? `H??c????H???5? ?%? #?%? h??????%? h??????%? h??????%? h?????%? h?????%? h?????%? h?????%? h?p????%? ?`????%? h ?P????%? h
?#????%? h
?0????%? h
?????%z h?????%r h??????%j h?????1?I??^H??H???PTI???#H??0#H??
#????????H?H?? H??t??H?Ð????????????UH??SH??=0 uK?`H?* H???`H??H??H9?s$fDH??H? ???`H?? H9?r??? H?[]?fff.?H?= UH??t?H??]`??]Ð?UH??SH???dH?%(H?E?1?Dž????Dž????Dž????H??????H???T???????H???????#H???????|H??0?????????Hc?H??H?H??????H??H???$?????????H????0????ƿ? `?Y?????
#H???
?????????H????0?????1 ???????????????????H??????H???????????d???H??????H???R???????????????????????ƿ? `??????%#H????????H???????6#H?????????
#H???`????H??????H?????????H?U?dH3%(t$?H??H??????H???????H??H???L????????H???[]?UH??H???}??u??}?u*?}???u!??!`?6????P
#?? `??!`H?????????UH?????????]?UH??}??u??U??E? ?]Ð???H?l$?L?d$?H?-? L?%? L?l$?L?t$?L?|$?H?\$?H??8L)?A??I??H??I???k???H??t1?#L??L??D??A??H??H9?u?H?\H?l$L?d$L?l$ L?t$(L?|$0H??8???Ð?????????????UH??SH?H H???t??`DH???H?H???u?H?[]Ð?H??_???H??exam.txtstudents out of did not pass the exam.D????`?????s?????????????????0p???XzRx
$H??? FJ
O ??;*3$"D8???A?C
I used this command: g++ main.cpp -o output.out
Is there something wrong with my command?
Thank you so much!!!
You're doing some dodgey things. As mentioned already, don't test eof. You actually need to test whether your input was successful and/or whether the stream is good. You can have a catch-all when you're reading streams:
while( infile )
{
//...
}
I mentioned also that you need to check that the value was read. It could be that an integer cannot be read because the input stream does not contain something that looks like an integer, or perhaps some other error occurred. Since you're only reading one integer at a time, you can test that operation by itself. If the stream was bad to begin with (eg the file could not be opened) it will fail straight away:
while( infile >> input[x] )
{
//...
}
I wouldn't generally use the above approach if reading more than one value each time, because the loop condition gets cluttered. Here's an alternative:
while( infile )
{
if( !(infile >> input[x]) ) {
cout << "Failed to read value " << x+1 << endl;
break;
}
//...
}
Let's roll with that, because it's more useful when you wanna find out what's going on. The next thing is that you have a fixed-size array with 100 values. If you read too many values, you are going to overflow. So you need to make sure this won't happen:
while( infile && x < 100 )
{
if( !(infile >> input[x]) ) {
cout << "Failed to read value " << x+1 << endl;
break;
}
cout << input[x] << endl;
if( input[x] < 50 ) {
fail++;
} else {
pass++;
}
x++;
}
Now, it seems to me that you're not even using the array, so why keep it at all? You could just read into a temporary value:
int grade;
if( !(infile >> grade) ) break;
// ...
But if you wanted to keep the array and didn't know how many grades you might end up reading, use a vector<int> instead of an int array. I'll show this with the simpler loop style:
std::vector<int> grades;
int grade;
while( infile >> grade )
{
grades.push_back(grade);
//...
}
Notice how I've used more descriptive variable names. Something like input doesn't tell you much about what it contains. That is the kind of variable name you'd get from an inexperienced programmer whose YouTube videos you should immediately boycott.
The last thing I'll suggest is using ifstream instead of fstream, because by default you don't need to open the file in read/write mode. You could supply flags to fstream::open, but why do that when you can just construct ifstream like this:
ifstream infile("exam.txt");
You also don't need to explicitly close it, because that will happen when infile's destructor is called.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main ()
{
string STRING;
ifstream infile;
infile.open ("names.txt");
while(!infile.eof) // To get you all the lines.
{
getline(infile,STRING); // Saves the line in STRING.
cout<<STRING; // Prints our STRING.
}
infile.close();
system ("pause");
}
I hope, this code can help you.

Sum all integers in a string C++

I have a C++ string in my code that is like:
"1 2 3 4 5 6 7 8"
I know the string is composed of integers separated by a space char. How can I sum them?
I'm quite a C++ newbie and in Java I'd simply do:
String str = "1 2 3 4 5 6 7 8";
int sum = 0;
for (int i = 0; i < str.split(" ").length; i++ {
sum += Integer.parse(str.split(" ")[i];
}
How can I do just like this with my string object in C++?
Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely, getting every single digit within it.
Thanks in advance!
Update: some guys nicely tried to help me but still it's not working. Perhaps because of some quirk of my problem which I haven't clarified before. So here it goes:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
freopen("variable-exercise.in", "r", stdin);
int sum = 0, start = 0;
string line;
while(getline(cin ,line)) {
istringstream iss(line);
while(iss >> start) {
sum += start;
}
cout << start << endl;
sum = start = 0;
}
return 0;
}
Ah, the input file contains the following:
1
3 4
8 1 1
7 2 9 3
1 1 1 1 1
0 1 2 5 6 10
So, for each line, the program must print the sum of all integers in the string line. This example would generate:
1
7
10
21
5
24
thanks
Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely
I guess you were given a good advice. With std::istringstream you could just read in values one after the other as you would read them from the standard input (or any other input stream).
For instance:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
// Suppose at some time you have this string...
std::string s = "1 2 3 4 5 6 7 8 9 10";
// You can create an istringstream object from it...
std::istringstream iss(s);
int i = 0;
int sum = 0;
// And read all values one after the other...
while (iss >> i)
{
// ...of course updating the sum each time
sum += i;
}
std::cout << sum;
}
Like this:
std::stringstream s("1 2 3 4 5 6 7 8 9");
int n = 0;
int x;
while (s >> x)
n += x;
std::cout << n << std::endl;
After your edit:
cout << start << endl;
This is wrong, you should be printing sum instead:
cout << sum << endl;
I used C code to solve this problem. Here's the final solution:
#include <stdio.h>
#include <string.h>
int main() {
char *c;
char line[100];
int x, sum = 0;
while(gets(line)) {
for(c = strtok(line, " "); c ; c = strtok(NULL, " ")) {
sscanf(c, "%d", &x);
sum += x;
}
printf("%d\n", sum);
sum = 0;
}
return 0;
}
Hope it helps anyone who might have the same problem!