cant get the output to show in my outputfile.txt - c++

#include <iostream>
#include <fstream>
void function(){
char ch;
int num;
int n;
int index = 0;
std::cout << "enter how manny letter you need to translate first: ";
std::cin >> n;
while (index < n){
std::cin >> ch >> num;
std::cout << char(ch+num)<<" ";
index++;
}
}
int main() {
std::ofstream outfile;
outfile.open("D:\\outfile.txt");
function();
outfile << function;
return 0;
}
this code asks for the number of letters you want to include ex:3
then you enter the letters with the a number, this number gets added to its ascii value
ex: a 1, out: b,
all of this is done in a void and i want the output "being the new letters" to be in the text file
the code always prints out 1 instead of the output letters inside the txt file

Related

How can I save a string input with blank space in c++ (I am using if else statement)

So I am trying to make a text multiplier , here is the code
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin >> x;
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Everything was fine until I came to know that it was not saving the text input with a blank space
I searched how to store string input with blank space and then changed the code but it didn't work.
The changed code was
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Please help
List item
If I understand what you want to do, you need to read the integer value, clear the remaining '\n' that is left in stdin by operator>>, and then use getline() to read the text you want to multiply, e.g.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
if (!(cin >> y)) { /* validate stream-state after EVERY input */
std::cerr << "error: invalid integer input.\n";
return 1;
}
/* clear remaining '\n' from stdin (and any other characters) */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "enter the text you want to multiply : ";
if (!getline (cin, x)) { /* validate stream state */
std::cout << "user canceled input.\n";
return 0;
}
for (int a = 1; a <= y; ++a)
cout << x << endl;
return 0;
}
Note: the use of isdigit(y) is superfluous. If you validate the input correctly, you determine whether a valid integer was entered at the time of the read simply by checking the stream-state after the read. If failbit is set, the user did not enter a valid integer.
While fine for test code, you will want to look at Why is “using namespace std;” considered bad practice?
Example Use/Output
$ ./bin/multiplytext
enter how many times you want to multiply the text : 3
enter the text you want to multiply : my dog has fleas
my dog has fleas
my dog has fleas
my dog has fleas
If I misinterpreted your goal, let me know and I'm happy to help further.
As seen from this answer, you are mixing the >> operator and getline() which causes syncing issues as getline is not waiting for the input to flush.
You can call either
cin.ignore();
or
cin.clear();
cin.sync();
just before getline().
Patched code:
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.ignore();
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}

Initialization and passing an array

I am trying to create a program that will draw using a single dimensional array however I am having a hard time initializing the array using only one cin statement. A sample input that the user in supposed to look like
1<space>2<space>34<space>3<space>2<space>1<space>0<space>10
#include<iostream>
using namespace std;
/*---------------------------------------------------------------------------------------
Prototypes
These are the prototype function(s) that will be used to to draw the row and columns
---------------------------------------------------------------------------------------*/
void draw(int nums);
//---------------------------------------------------------------------------------------
int main(){
const int MAX = 100;
int chart[MAX];
int nums;
cout << "Enter numbers for the chart" << endl;
cin >> nums;
draw(nums);
return 0;
}
void draw(int nums) {
cout << endl;
int row;
for (row = 0; row < nums; ++row) {
cout << "*" << endl;
}
}
How would I initialize the array with the sample input given and then pass it to a function to be used to draw
Here's a simple (perhaps unsafe but then again don't use std::cin for safety) implementation that seems to work for reading in the numbers:
#include <iostream>
#include <list>
#include <sstream>
int main()
{
std::cout << "Input numbers: ";
// get input line
std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
// read numbers
std::list<int> numbers;
while(ss) {
int number;
ss >> number;
ss.ignore();
numbers.push_back(number);
}
// display input
for(const auto number: numbers) {
std::cout << number << std::endl;
}
return 0;
}
And here's a sample run:
$ ./a.out
Input numbers: 1 2 3 4
1
2
3
4
I think you need a parse to decode the input. something like following:
void parse(const std::string& input, int output[], int MaxNum)
{
// parse the integer from the string to output.
}
int main(){
......
std::string input;
cout << "Enter numbers for the chart" << endl;
cin >> input;
parse(input, chart, MAX);
......
}
Here is a version of a program that lets you input a series of numbers with only one cin line with the help of stringstream, but the only difference is that it stores the input in a vector. It then draws a histogram chart based on the input.
Just press the <ENTER> key twice to let the program know that you are done with the inputting of the numbers.
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
vector<int> Vector;
string line;
void drawchart(int max);
int main() {
cout<<"Chart drawing program ( Histogram) \n";
cout<<"Enter a series of numbers. \n";
cout<<"Seperate with a space, press <ENTER> TWICE to end input \n";
cout<<" (e.g 2 3 4 5 6) > ";
if(!getline(cin, line)) return 1;
istringstream iss(line);
copy( istream_iterator<int>(iss), istream_iterator<int>(), back_inserter(Vector));
copy(Vector.begin(), Vector.end(), ostream_iterator<int>(cout, ", "));
cout<<"\nDrawing chart.. \n\n";
drawchart( Vector.size() );
cout<<"Press ANY key to close.\n\n";
cin.ignore();cin.get();
return 0;
}
// draws a chart or hjistogram
void drawchart(int max){
for( int i = 0; i < max ; i++){
for(int j = 0; j < Vector[i]; j++) cout << "*";
cout << endl;
}
}

Input values into a vector until the end of input?

So I want the user to input something like this:
0 15 72 34 92 8
and I want to fill a vector of integers with these numbers.
Here is what I have:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> V;
cout << "Please enter the numbers separated by \n";
cout << "spaces, then press the \"Enter\" key.\n\n";
int temp;
while (cin >> temp)
{
V.push_back(temp);
}
// The programs gets to this point and continuously asks for input
// Print the vector
cout << "The vector contains [ ";
for(int i = 0; i < V.size(); i++)
cout << V.at(i) << " ";
cout << "], ";
}
Modify your code based on this example. It takes input from user until user enters -1.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int number;
vector<int> userInput;
do
{
cout << "Enter a number (-1 to quit): ";
cin >> number;
userInput.push_back(number);
} while (number != -1);
for (vector < int >::iterator it = userInput.begin(); it < userInput.end() - 1; it++)
{
cout << endl << *it;
}
system("pause");
return 0;
}
First, read the entire line as a string using getline and after that fetch every integer and push it into the integer array.
vector<int> v;
string buffer;
int data;
getline(cin, buffer);
istringstream iss(buffer);
while (iss >> data)
v.push_back(data);

Use for loop count being ignored when using cin in C++

I have a for loop set up to take in user input X amount of times based on the number of nodes used for an adjacency list for this depth first search algorithm.
int nodeNum;
cout << "Number of nodes?: " << endl;
cin >> nodeNum;
cout << "Names: " << endl;
for (int i = 0; i < nodeNum; i++)
{
getline(cin, tempName);
v.push_back(tempName); //pushing the name of node into a vector
}
When I submit this into the online compiler of my university and GCC, it skips the last input. Example - I put in the number 8, it'll only take 7 nodes. How can I fix this?
The statement cin >> nodeNum reads the integer but leaves the file pointer immediately after the integer, but before the newline.
So the first iteration of the loop reads that newline as the first line. You can see this effect with:
#include <iostream>
using namespace std;
int main(void) {
int nodeNum;
string tempName;
cout << "Number of nodes?\n";
cin >> nodeNum;
cout << "Names:\n";
for (int i = 0; i < nodeNum; i++)
{
getline(cin, tempName);
cout << "[" << tempName << "]\n";
}
return 0;
}
with the sample run:
Number of nodes?
2xx
Names:
[xx]
aaa
[aaa]
One way to fix that is to place:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
immediately after the cin >> nodeNum - this clears out the characters until the end of the current line. You need to include the <limits> header file to use that.
Applying that change to the example code above:
#include <iostream>
#include <limits>
using namespace std;
int main(void) {
int nodeNum;
string tempName;
cout << "Number of nodes?\n";
cin >> nodeNum;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Names:\n";
for (int i = 0; i < nodeNum; i++)
{
getline(cin, tempName);
cout << "[" << tempName << "]\n";
}
return 0;
}
improves the situation markedly:
Number of nodes?
2xx
Names:
aaa
[aaa]
bbb
[bbb]

How to cin values into a vector

I'm trying to ask the user to enter numbers that will be pushed into a vector,
then using a function call to count these numbers.
why is this not working? I'm only able to count the first number.
template <typename T>
void write_vector(const vector<T>& V)
{
cout << "The numbers in the vector are: " << endl;
for(int i=0; i < V.size(); i++)
cout << V[i] << " ";
}
int main()
{
int input;
vector<int> V;
cout << "Enter your numbers to be evaluated: " << endl;
cin >> input;
V.push_back(input);
write_vector(V);
return 0;
}
As is, you're only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace
cin >> input;
V.push_back(input);
with
while (cin >> input)
V.push_back(input);
What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:
while ((cin >> input) && input != 9999)
V.push_back(input);
will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.
You need a loop for that. So do this:
while (cin >> input) //enter any non-integer to end the loop!
{
V.push_back(input);
}
Or use this idiomatic version:
#include <iterator> //for std::istream_iterator
std::istream_iterator<int> begin(std::cin), end;
std::vector<int> v(begin, end);
write_vector(v);
You could also improve your write_vector as:
#include <algorithm> //for std::copy
template <typename T>
void write_vector(const vector<T>& v)
{
cout << "The numbers in the vector are: " << endl;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}
Other answers would have you disallow a particular number, or tell the user to enter something non-numeric in order to terminate input. Perhaps a better solution is to use std::getline() to read a line of input, then use std::istringstream to read all of the numbers from that line into the vector.
#include <iostream>
#include <sstream>
#include <vector>
int main(int argc, char** argv) {
std::string line;
int number;
std::vector<int> numbers;
std::cout << "Enter numbers separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number)
numbers.push_back(number);
write_vector(numbers);
}
Also, your write_vector() implementation can be replaced with a more idiomatic call to the std::copy() algorithm to copy the elements to an std::ostream_iterator to std::cout:
#include <algorithm>
#include <iterator>
template<class T>
void write_vector(const std::vector<T>& vector) {
std::cout << "Numbers you entered: ";
std::copy(vector.begin(), vector.end(),
std::ostream_iterator<T>(std::cout, " "));
std::cout << '\n';
}
You can also use std::copy() and a couple of handy iterators to get the values into the vector without an explicit loop:
std::copy(std::istream_iterator<int>(stream),
std::istream_iterator<int>(),
std::back_inserter(numbers));
But that’s probably overkill.
you have 2 options:
If you know the size of vector will be (in your case/example it's seems you know it):
vector<int> V(size)
for(int i =0;i<size;i++){
cin>>V[i];
}
if you don't and you can't get it in you'r program flow then:
int helper;
while(cin>>helper){
V.push_back(helper);
}
If you know the size of the vector you can do it like this:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (auto &it : v) {
cin >> it;
}
}
One-liner to read a fixed amount of numbers into a vector (C++11):
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <cstddef>
int main()
{
const std::size_t LIMIT{5};
std::vector<int> collection;
std::generate_n(std::back_inserter(collection), LIMIT,
[]()
{
return *(std::istream_iterator<int>(std::cin));
}
);
return 0;
}
If you know the size use this
No temporary variable used just to store user input
int main()
{
cout << "Hello World!\n";
int n;//input size
cin >> n;
vector<int>a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//to verify output user input printed below
for (auto x : a) {
cout << x << " ";
}
return 0;
}
You need a second integer.
int i,n;
vector<int> V;
cout << "Enter the amount of numbers you want to evaluate: ";
cin >> i;
cout << "Enter your numbers to be evaluated: " << endl;
while (V.size() < i && cin >> n){
V.push_back(n);
}
write_vector(V);
return 0;
You probably want to read in more numbers, not only one.
For this, you need a loop
int main()
{
int input = 0;
while(input != -1){
vector<int> V;
cout << "Enter your numbers to be evaluated: " << endl;
cin >> input;
V.push_back(input);
write_vector(V);
}
return 0;
}
Note, with this version, it is not possible to add the number -1 as it is the "end signal".
Type numbers as long as you like, it will be aborted when you type -1.
cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as
int input;
cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
while(input != 10000) {
cin >> input;
V.push_back(input);
}
write_vector(V);
You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.
int main() {
int sizz,input;
std::vector<int> vc1;
cout<< "How many Numbers you want to enter : ";
cin >> sizz;
cout << "Input Data : " << endl;
for (int i = 0; i < sizz; i++) {//for taking input form the user
cin >> input;
vc1.push_back(input);
}
cout << "print data of vector : " << endl;
for (int i = 0; i < sizz; i++) {
cout << vc1[i] << endl;
}
}
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string>V;
int num;
cin>>num;
string input;
while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
//cin>>input;
V.push_back(input);
num--;
if(num==0)
{
vector<string>::iterator it;
for(it=V.begin();it!=V.end();it++)
cout<<*it<<endl;
};
}
return 0;
};
#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
vector<string> v;
string line,t;
getline(cin,line);
istringstream iss(line);
while(iss>>t)
v.push_back(t);
vector<string>::iterator it;
for(it=v.begin();it!=v.end();it++)
cout<<*it<<endl;
return 0;
}
In this case your while loop will look like
int i = 0;
int a = 0;
while (i < n){
cin >> a;
V.push_back(a);
++i;
}
The initial size() of V will be 0, while int n contains any random value because you don't initialize it.
V.size() < n is probably false.
Silly me missed the "Enter the amount of numbers you want to evaluate: "
If you enter a n that's smaller than V.size() at that time, the loop will terminate.
Just add another variable.
int temp;
while (cin >> temp && V.size() < n){
V.push_back(temp);
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x,n;
cin>>x;
vector<int> v;
cout<<"Enter numbers:\n";
for(int i=0;i<x;i++)
{
cin>>n;
v.push_back(n);
}
//displaying vector contents
for(int p : v)
cout<<p<<" ";
}
A simple way to take input in vector.
These were two methods I tried. Both are fine to use.
int main() {
int size,temp;
cin>>size;
vector<int> ar(size);
//method 1
for(auto i=0;i<size;i++)
{ cin>>temp;
ar.insert(ar.begin()+i,temp);
}
for (auto i:ar)
cout <<i<<" ";
//method 2
for(int i=0;i<size;i++)
{
cin>>ar[i];
}
for (auto i:ar)
cout <<i<<" ";
return 0;
}
would be easier if you specify the size of vector by taking an input :
int main()
{
int input,n;
vector<int> V;
cout<<"Enter the number of inputs: ";
cin>>n;
cout << "Enter your numbers to be evaluated: " << endl;
for(int i=0;i<n;i++){
cin >> input;
V.push_back(input);
}
write_vector(V);
return 0;
}
I ran into a similar problem and this is how I did it. Using &modifying your code appropriately:
int main()
{
int input;
vector<int> V;
cout << "Enter your numbers to be evaluated: "
<< '\n' << "type "done" & keyboard Enter to stop entry"
<< '\n';
while ( (cin >> input) && input != "done") {
V.push_back(input);
}
write_vector(V);
return 0;
}
cout << "do you like to enter the sem 2 score "<<endl;
cin >> sem2;
if (sem2 == 'Y' || sem2 == 'y')
{
cout << "enter your subject count ";
cin >> subjectcount;
cout << " enter your scores :";
for (int i = 0; i < subjectcount; i++)
{
double ip;
cout << (i+1) << " st score ";
cin >> ip;
sem2score.push_back(ip);
}
}
You can extract numbers by this way:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int aux;
char c='\n';
char a;
while(scanf("%d", &aux))
{
cout<<aux<<endl;
if(scanf("%c",&a) && a==c)
break;
}
return 0;
}