Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to convert a double* to string in C++:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
double *f = new double[5];
for(i = 0; i < 5; i++)
{
f[i] = 5;
}
string f_str;
//this is for double to string
//f_str = std::to_string(f);
//i want for double*
cout << f_str << '\n';
delete [] f;
return 1;
}
Try to use to_string:
std::stringstream ss;
for(i = 0; i < 5; i++)
{
f[i] = 5;
ss << std::to_string(f[i]) << ", ";
}
string f_str = ss.str();
Try this
#include <iostream>
#include <string>
#include <sstream>
int main( )
{
const int SIZE(5);
double *f = new double[SIZE];
// fill data
for(int i(0); i < SIZE; i++)
f[i] = 5;
std::string doubArray2Str;
for(int i(0); i < SIZE; ++i){
std::ostringstream doubleStr;
if ( i == SIZE - 1 )
doubleStr << f[i];
else
doubleStr << f[i] << ",";
doubArray2Str += doubleStr.str();
}
std::cout << doubArray2Str << std::endl;
delete [] f;
return 0;
}
You can try the following code. Hope this will help you buddy. Thanks.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#define MAX 1000
using namespace std;
typedef long long ll;
string DOUBLE_TO_STRING(double data)
{
string number;
stringstream out ;
out << data;
number = out.str();
return(number);
}
int main()
{
ll n;
while(cin >> n)
{
double a[MAX];
vector<string> str;
for(ll i=0; i<n; i++){
cin >> a[i];
str.push_back(DOUBLE_TO_STRING(a[i]));
}
for(ll i=0; i<str.size(); i++)
cout << str[i] << "\n";
}
return 0;
}
Related
In the following code for loop returns me 5 values [0,1,2,3,4]. I want to get 5 text files with the name h_0.0, h_1.0, h_2.0, h_3.0, h_4.0 and h_0.0 should store first number of for loop i.e.,0 file h_1.0 should store second number of for loop i.e., 1 and so on.
#include <iostream>
using namespace std;
int *name()
{
static int n[5];
for (int i = 0; i < 5; i++)
{
n[i] = i;
}
return n;
}
int main()
{
int *p;
p = name();
for (int i = 0; i < 5; i++)
{
cout << *(p + i) << endl;
}
return 0;
}
If I understand well what you want to do, here is some basic solution, for demo,
creating files in current folder:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int* name() {
static int n[5];
for (int i = 0; i < 5; i++) {
n[i] = i;
}
return n;
}
int main() {
int* p;
p = name();
for (int i = 0; i < 5; i++)
{
int fn = *(p + i);
std::stringstream ss;
ss << fn;
std::string fname = "h_" + ss.str();
fname += ".0";
std::ofstream f(fname.c_str());
if (f.good()) {
f << fn;
cout << "file h_" << fn << ".0 created" << endl;
}
}
return 0;
}
Use filestream.
#include <fstream> // include filestream
#include <sstream> // for storing anything that can go into a stream
#include <string>
int main()
{
std::string nameholder;
std::ofstream outputstream;
for (int i = 0; i < 5; i++)
{
nameholder = "h_"; // reset name every loop
std::stringstream sstreamholder; // remake stringstream every loop
sstreamholder << i; // store current number in stringstream
nameholder += sstreamholder.str() + ".0"; // append what sstreamholder currenlty has and the file extension .0
outputstream.open(nameholder); // write the filename with the updated name
outputstream << i << std::endl; // write the number in the file
outputstream.close(); // close the file so it's ready for the next open
}
return 0;
}
Need some help with the problem.
When I compile my code below, it gives me this error:
error: invalid conversion from " int* " to " int "
I want to create a calculatePercentage function, so I can use the value when I call it.
void calculatePercentage(int voteResult[],int percentage[])
const int NO_OF_CANDIDATE = 10;
int main()
{
ifstream input("votes.txt",ios::in);
string candidates[NUMBER_OF_CANDIDATE];
int voteResult[NUMBER_OF_CANDIDATE];
int percentage[NUMBER_OF_CANDIDATE];
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++) {
input >> candidates[i] >> voteResult[i];
}
calculatePercentage(voteResult, percentage); // error happened here.
return 0;
}
void calculatePercentage(int voteResult[],int percentage[])
{
int totalVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++)
{
totalVotes += votes[i];
}
for (int j = 0; j < NUMBER_OF_CANDIDATE; j++)
{
double wk_percentage = static_cast<double>{votes[j])/totalVotes;
percentage[j]=static_cast<int>(wk_percentage*100);
}
}
The code you posted has a bunch of errors.
calculatePercentage() definition is missing the closing ';'
probable name mismatch between NO_OF_CANDIDATE and NUMBER_OF_CANDIDATE
missing #include <fstream> (using ifstream)
missing #include <string>
missing std:: namespace before ifstream and string
votes not declared anywhere (should it be voteResult?)
wrong opening curly bracket instead in static_cast<double>{votes[j])/totalVotes;
...
Let alone the way you do calculation and parameter passing...
The following edited code should compile, not sure if it works as you expected:
#include <fstream>
#include <string>
void calculatePercentage(int voteResult[], int percentage[]);
const int NUMBER_OF_CANDIDATE = 10;
int main()
{
std::ifstream input("votes.txt");
std::string candidates[NUMBER_OF_CANDIDATE];
int voteResult[NUMBER_OF_CANDIDATE];
int percentage[NUMBER_OF_CANDIDATE];
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++) {
input >> candidates[i] >> voteResult[i];
}
calculatePercentage(voteResult, percentage); // error happened here.
return 0;
}
void calculatePercentage(int voteResult[], int percentage[])
{
int totalVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++)
{
totalVotes += voteResult[i];
}
for (int j = 0; j < NUMBER_OF_CANDIDATE; j++)
{
double wk_percentage = static_cast<double>(voteResult[j]) / totalVotes;
percentage[j] = static_cast<int>(wk_percentage*100);
}
}
Also on Ideone.
Thanks for everyone's comment. I skipped some statements and made some typos when posting them. I fixed them as follows. The only error occurred is that still cannot convert " int* " from " int". Just don't know how to solve it.
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void calculatePercentage(int voteResult[],int percentage[]);
const int NUMBER_OF_CANDIDATE = 10;
int main()
{
ifstream input("votes.txt",ios::in);
string candidates[NUMBER_OF_CANDIDATE];
int vote[NUMBER_OF_CANDIDATE];
int percentage[NUMBER_OF_CANDIDATE];
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++) {
input >> candidates[i] >> vote[i];
}
calculatePercentage(voteResult, percentage); // error happened here.
return 0;
}
void calculatePercentage(int voteResult[],int percentage[])
{
int totalVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++)
{
totalVotes += votes[i];
}
for (int j = 0; j < NUMBER_OF_CANDIDATE; j++)
{
double wk_percentage = static_cast<double>(votes[j])/totalVotes;
percentage[j]=static_cast<int>(wk_percentage*100);
}
}
I am working on creating a simulation of a test that will
1. randomize multiple choice answers
2. display the choices from a) b) c) d)
I have both codes done separately however can I use on for-loop to go about displaying this? Is this the best way to do this? All help is appreciated thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE;
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
}
//separate code for part 2: choices from a-g
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << " ";
}
}
You can iterate over both arrays and stop when smaller will ends
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
cout << choices[i] << " " << animals[i] << ", ";
}
}
Also, consider that if you want to use fixed-size array, you can use std::array:
#include <array>
std::array<string, TEST_SIZE> animals = {...};
And for shuffling you can use std::shuffle from 'algorithm' header .
I want to write random sorted data to a file. I'm using g++, but after running the program there was no data saved to the file.
This is the code:
#include <string>
// basic file operations
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int ra;
int pp = 0;
ofstream myfile("fi21.txt");
myfile.open("fi21.txt");
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
ra = (rand()) + pp;
pp = ra;
std::string vv;
vv = "1,";
vv += i;
vv += ",";
vv += ra;
vv += "\n";
// myfile << vv;
myfile.write(vv.c_str(), sizeof(vv));
}
}
// myfile.close();
return 0;
}
Your code should/could look like this:
#include <string>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int ra;
int pp = 0;
ofstream myfile("fi21.txt"); // This already opens the file, no need to call open
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
ra = rand() + pp;
pp = ra;
// This will concatenate the strings and integers.
// std::string::operator+= on the other hand, will convert
// integers to chars. Is that what you want?
myfile << "1," << i << "," << ra << "\n";
}
}
return 0;
}
That superfluous call was the major problem, but also note that your attempt:
myfile.write(vv.c_str(), sizeof(vv));
has a mistake - sizeof(vv) is the number of bytes std::string takes on the stack, not how long it is. std::string::length or std::string::size is for that. Why to use the above at all, when you can myfile << vv;? I actually didn't even use std::string in the above code.
This is my first post, so please be understanding for me :)
I would like to use vector of strings to make sort data easy, but I need this string also to function fun1. So I would like to convert char* word to string str but i can't manage to do it. I was searching answer for my question but I didn't find.
Please help, here is code:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
vector <string> tab;
vector <string> tab2;
int l['Z'+1];
void fun1(char *t)
{
for(int i = 0; t[i]; i++)
l[t[i]]++;
int j = 0;
for(int i = 'A'; i <= 'Z'; i++)
if(l[i])
{
t[j++] = i;
l[i--]--;
}
}
int main()
{
char * word;
string str;
ios_base::sync_with_stdio(0);
int z;
int n;
cin >> z;
while(z--)
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> word;
fun1(word);
str.assign(word, sizeof(word));
tab.push_back(str);
}
sort(tab.begin(), tab.end());
for(int i = 0; i < tab.size(); i++)
cout << tab[i] << endl;
}
}
Firstly, I have no idea, why you want to convert char* to string. In your solution firstly you have to allocate memory for chars
char *word = new char[HOW_MANY_CHARS]
But there is better solution. You can write:
cin >> str;
fun1(str);
tab.push_back(str);
And you have to change fun1 to:
void fun1(string &t);