I have written this program in C++ that reads an input.txt file containing these numbers
7
18
5
15
131
11
13
287
The program adds to the array the first value 7, then in the next seven numbers there's random values (such as 0, 4659174, 0, 4778144 etc) and then it prints 7 and 18 and then eight more random numbers and then you can see printed 7, 18, 5 and so on until the last eight numbers are what is actually in the input.txt file.
How can I get it to show only the numbers that are present in the input.txt file instead of all of these random values? Here's my code so far:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <stdlib.h>
using namespace std;
int main(){
int myArray[10];
int i = 0;
ifstream input("input.txt");
string number = "";
char next_letter = '\0';
while (input.get(next_letter)){
while (isdigit(next_letter) && !input.eof()){
number += next_letter;
input.get(next_letter);
}
int val = 0;
val = atoi(number.c_str());
myArray[i++] = val;
for(int i = 0; i < 8; i++)
{
cout << "array contents are: " << myArray[i] << endl;
}
number = "";
}
return 0;
}
Please consider the following code:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main(){
long myArray[10];
int i = 0;
ifstream input("input.txt");
string number = "";
const int MAX_LEN = 100;
char number_str[MAX_LEN];
while(input.getline(number_str, MAX_LEN - 1, ' ')){
char* end;
myArray[i++] = std::strtol(number_str, &end, 10);
}
cout << "array contents is: ";
for(int k = 0; k < i; k++)
{
cout << myArray[k] << " ";
}
cout << endl;
return 0;
}
The getline does the reading until the ' ' and conversion is done by strtol. Please note that it input numbers are long int by default.
Related
printing only those strings that include 2-digit number
the text inside "myFile.txt is
{the pink double jump 34
the rising frog 2
doing the code 11
nice 4 }
"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <algorithm>
int main()
{
std::string path = "myFile.txt";
std::ifstream de;
de.open(path);
if (!de.is_open()) {
std::cout << "nah";
}
else {
std::cout << "file is opened";
std::string str;
while (!de.eof()) {
std::getline(de, str);
for (int i = 0; i < str.length(); i++) {
int aa = 10;
if (str[i] > aa) {
str = "0";
}
}
std::cout << str << "\n\n";
}
}
}
what am I doing wrong? how can I check if there is any 2-digit number inside the string?
You could use stoi as follows:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::ifstream inp("test.txt");
std::string word;
std::vector<std::string> listOfTwoDigitStrings;
while(inp>>std::ws>>word) {
if(word.length() == 2) {
int num = std::stoi(word);
if(num >= 10 && num <= 99) {
listOfTwoDigitStrings.push_back(word);
}
}
}
for(const auto& word: listOfTwoDigitStrings) {
std::cout<<word<<' ';
}
std::cout<<'\n';
return 0;
}
which has the output
34 11
when test.txt contains
{the pink double jump 34
the rising frog 2
doing the code 11
nice 4 } "
P.S.: As you're looking for strings, just read in strings rather than lines and then reading off strings from that line. Reading off strings just makes it simpler since it boils down to just narrowing down to 2-digit strings and then just verifying whether they are numbers or not. Also, as mentioned in the comments, refrain from !file.eof() code.
What I'm trying to do is this:
User enters a string (For example: "Hello")
The program returns the same string, but in a random order(It can be "elHlo" or any other order possible)
So far I've written this code, but the problem is that sometimes the randomly generated numbers are the same, so it might print the same indexes(letters) twice or more times:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
for(unsigned int j=0; j<text.length(); j++){
int randomLetter = rand()%text.length();
cout << text.at(randomLetter);
}
return 0;
}
Can anyone help me fix it?
You can use std::shuffle (since C++11):
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
std::mt19937 g(time(0));
std::shuffle(text.begin(), text.end(), g);
cout << text;
return 0;
}
Or std::random_shuffle (if you are using old specification):
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
std::random_shuffle(text.begin(), text.end());
cout << text;
return 0;
}
Instead of calling rand() one time, which can generate an index you have called before, you can keep generating a new index while keeping tracking of all generated indices in a hashtable.
std::unordered_map<int, bool> done;
for (unsigned int j = 0; j < text.length(); j++) {
int randomLetter = rand() % text.length();
while (done[randomLetter] == true) // while it's been marked as finished, generate a new index.
randomLetter = rand() % text.length();
cout << text.at(randomLetter);
done[randomLetter] = true; // mark it as finished.
}
Alternatively, you can use std::random_shuffle instead, which should save you the hassle.
std::random_shuffle (text.begin(), text.end());
std::cout << text << '\n';
I'm trying to create a file that generates random numbers, then I want the program to call those random numbers and print them out. 1st; the srand
(time(NULL)) function is giving me an error, 2nd; i want to check wether the loop and the formula i used to get random numbers are correct.
Thanks.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int rand(int x);
int main(int argc, char* argv[])
{
ofstream outputFile;
outputFile.open("fileTest.txt");
int i;
for (i =0; i<23; i++)
{
outputFile << rand(i) <<endl;
}
ifstream inputFile;
inputFile.open ("fileTest.txt");
int ranNum[i];
for (int i = 190; i <= 270; i++)
{
ranNum[i] = (rand() % (270-190+1)+ 190);
inputFile>> ranNum[i];
cout<<ranNum [i]<<" "<<endl;
}
system("pause");
return 0;
}
Try this:
#include <iostream>
#include <string>
#include <time.h>
#include <limits>
#include <fstream>
using namespace std;
void generate_random_file(int size_of_array = 100) {
ofstream fout; // open the stream
fout.open("data_" + std::to_string(size_of_array) + ".txt"); // open the file
if (!fout.is_open())
cout << "Error: cannot open the file!\n";
else
{
srand(time(0));
int min = 0;//numeric_limits<int>::min();
int max = 100;//numeric_limits<int>::max();
int buf;
for (int i = 0; i < size_of_array; i++)
{
buf = min + rand() % (min - max + 1);
fout << buf << " ";
}
fout << endl;
}
fout.close(); // close the file
}
int main()
{
generate_random_file();
return 0;
}
I assume your goal is to generate set of random numbers and write them into file. Using your base code below you'll find working version. Please note some comments:
int rand(int x); This is a declaration, you cannot leave it as it
is, also there is proper implementation of this function in one of
the libraries you included.
Using srand before rand is
recommended to initialize pseudo-random value generator. You are
trying to use srand(time(NULL)) which in every execution initializes
with different
value. If you use static value, i.e. srand(0) you get the same
random sequence each time.
Also I assume you don't need to read from file, so following code
generates array of random integers, prints them and save into file.
At the end of writing into file/stream you need to close this file
outputFile.close().
cin.get() gives you a 'pause' you are looking for, just press
to exit from program.
If you are willing to go deeper into C++ here you have some handy resource.
Here is a code:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main ()
{
ofstream outputFile;
outputFile.open("fileTest.txt");
srand(time(NULL));
int range = 270 - 190;
int ranNum[range];
for (int i = 0; i <= range; i++)
{
ranNum[i] = 190 + 1 + rand () % range;
cout << ranNum[i] << " " << endl;
}
outputFile.close();
cin.get();
return 0;
}
Here is an online compiler with ready program
beginner here
i wrote the below in C++, it's a short program that currently takes 2 words as inputs, and outputs the same words back but the words are split into even and odd instead. I would like to be able to do this for 'T' words instead, but I can't figure it out. I would like to be able to first input the number of words that will follow, for example 10. Then to input the words and get T results back. So instead of just 2 words, an unlimited amount with the user specifying.
I need to put the below into a function and go from there sometime, but I want to learn the best technique to do so - any advice please?
Thanks!
Alex
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
Think I got it here, I was over-thinking this one
I put it in a for loop, as below - so any number of words can be input, user has to input the number of test cases at the
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++){
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
}
return 0;
}
Ultimately, you are performing the same task N times.
First, let's discuss how to store the information. Functionally, we have one string as input which yields two strings as output. std::pair (from <utility>) lets us easily represent this. But for sake of even-odd, std::array might be a better representation for us. Since we have a variable number of words as input, a variable number of std::array will be output. std::vector (from <vector>) is our friend here.
Second, let's discuss how to process the information. Using named variables for each output component does not scale, so let's switch to a fixed array (noted below as array<string,2>. By switching to a fixed array for output, addressing each split becomes a function of the loop index (index % 2). Below is a solution that generalizes on a known split size at compile time.
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}
I can't seem to figure out whats causing the issue. I want the program to read the list of numbers from the file, print out the list, then total up all the numbers, but when I try to find the total, I cannot convert the string values into integer values
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int total = 0;
string line;
ifstream myfile;
myfile.open("random.txt");
while (getline(myfile, line)) {
cout << line << endl;
total = total + static_cast<int>(line);
}
cout << total;
}
If you are using C++ 11 try stoi:
total = total + stoi(line);
You probably want
total = 0;
for (int i = 0; i < line.length(); ++i) {
total = total + static_cast<int>(line[i]);
}
Edit:
I misunderstood the question. The following code should work.
The input file is
11 22
10
and the result is 43.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
int total = 0;
string line;
ifstream myfile;
int line_int = 0;
myfile.open("random.txt");
while (getline(myfile, line)) {
cout << line << endl;
istringstream iss(line);
while(iss >> line_int)
total = total + line_int;
}
cout << total;
}