C++ Code removes first character from vector to int conversion - c++

Below is my code, CP Code represents a template.
For sometime, I have been trying to figure out why the function splitStringOutInt removes the first character. For example, the input is 11 12 13, but the output is [1, 12, 13]. I am very lost, also I am new to C++ so if there is a better method to convert a string line input to an array/vector, please let me know.
// START CP CODE
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string cinLine()
{
cin.ignore();
string tempVar {};
getline(cin, tempVar);
return tempVar;
}
long long int stringToInt(string num)
{
long long int convertedVal = 0;
stringstream strConverterOBJ;
strConverterOBJ << num;
strConverterOBJ >> convertedVal;
return convertedVal;
}
int printIntVector(vector<long long int> lst)
{
cout << "[";
for(int i=0; i<lst.size(); i++){
if(i!=lst.size()-1) {
cout << lst.at(i) << ", ";
}else{
cout << lst.at(i);
}
}
cout << "]" << endl;
return 0;
}
string printStrVector(vector<string> lst)
{
for(int i=0; i<lst.size(); i++){
if(i!=lst.size()-1) {
cout << lst.at(i) << endl;
}else{
cout << lst.at(i);
}
}
return "";
}
vector<long long int> splitStringOutInt(char divider, string str)
{
vector<long long int> intList;
for(long long int j=0; j<=str.length(); j++){
long long int answer {};
if(str[j] == divider || j == str.length()){
answer = stringToInt(str.substr(0, j+1));
str.erase(0,j+1);
intList.insert(intList.end(), answer);
j=0;
}
}
return intList;
}
// END CP CODE
int main()
{
vector<long long int> inp1;
inp1 = splitStringOutInt(' ', cinLine());
printIntVector(inp1);
return 0;
}

Related

read int per line c++ error needs solution

hey guys I need help for my read code seems not working properly here's the code. The problem is as shown in the picture, the compiler are supposed to display all 1 million int value but it seems that my write or the display code was wrong. It shows nothing like it's not even reading.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include <omp.h>
#include <ctime>
#include <cstdlib>
using namespace std;
int* CreateArray( int*);
void shellSortParallel( int*, int);
void shellSortSequential(int*, int);
void InsertSort( int*, int, int, int);
int main()
{
int array_size = 1000000;
int n=0;
int* arr=new int[array_size];
ifstream fin("OUTPUT1.txt");
if(! fin)
{
cout << "File could not be opened." << endl;
}
else
{
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
}
fin.close();
int length = 1000000;
double endTime = 0, startTime = 0, totalTime = 0;
double start, end;
cout << "Program is now sorting using shell sort" <<endl;
startTime = time(NULL);
start = omp_get_wtime();// Start performance timer 1 run
shellSortParallel(arr, length);//Run the algorithm
end = omp_get_wtime();// End performance timer 1 run
endTime = time(NULL);
totalTime = endTime - startTime;
cout << "This is the time it took to run. " << totalTime << endl;// time in seconds
int stupid = 0;
cin >> stupid;
cout << "Program has completed all tasks!!" << endl;
return 0;
}
void shellSortParallel(int array[], int length)
{
int h;
int j = 0;
int temp = 0;
int i = 0;
for(h =length/2; h > 0; h = h/2)
{
#pragma omp parallel for shared( array, length, h, i) default(none)
for( i = 0; i < h; i++)
{
//int ID = omp_get_thread_num();
InsertSort(array, i, length, h);
}
}
}
void InsertSort(int arr[], int i, int length, int half)
{
//cout << ID << " ";
int temp = 0;
int j = 0;
for (int f = half + i; f < length; f = f + half)
{
j = f;
while(j > i && arr[j-half] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-half];
arr[j-half] = temp;
j = j -half;
}
}
}
and here is the short version of the file that I'm going to read. Its a random number between 1 to 1million per line
2377763
88764877846
281327
60
625
86
646127818
14551
2177645
32033
1826761
555173
3415445377
32430
1101
any help would be much appreciate, thank you before
By if(fin>>data) you are not just testing, but retrieving data from stream. I suggest use ifs.good() for testing. Overall, you can write such a code instead
std::ifstream fin ("OUTPUT1.txt", std::ifstream::in);
char c = fin.get();
while (fin.good())
{
std::cout << c;
c = fin.get();
}
arr[n-1] = '\0'; is not correct because it's not an array of character so don't mind.
to correct it:
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
why allocating such huge array of integers? use vector is a good thing:
vector<int> vec;
ifstream fin("OUTPUT1.txt");
int data;
while(fin >> data)
{
vec.push_back(data);
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << endl;
fin.close();
88764877846 out band of an integer which causes the loop stop reading so you have to either get values as strings then convert into __int64 or __int128
to read values as strings:
string sLine;
int nLines = 0;
ifstream fin("OUTPUT1.txt");
// first read to get number of lines
while(getline(fin, sLine))
nLines++;
//create an array of strings
string* pstrValues = new string[nLines];
// set the get pointer to the beginning of file because the previous read moved it
fin.clear();
fin.seekg(0, ios::beg);
int i = 0;
while(getline(fin, sLine))
{
pstrValues[i] = sLine;
i++;
}
cout << "Displaying Array..." << endl << endl;
for( i = 0; i < nLines; i++)
cout << pstrValues[i] << endl;
fin.close();
now you have an array of strings convert it to int values but you must convert to __int64 because as I said there are values bigger than size of int (4bytes)

how to save the sorted arrays in textfile?

I have a program that sorted arrays how can i save in text file?
for example: the sorted arrays is: 1, 2, 3, 4, 5.
how can i save in text file named. Sorted elements".
I've tried many ways but the sorted array wouldn't save in text file.
I am a newbie so I find it difficult.
here is my code.
#include <iostream>
using namespace std;
int main() {
cout << "Enter number of element:";
int n; cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cout << "element number " << (i+1) << " : ";
cin >> a[i];
}
int e=1, d=3;
int i, j, k, m, digit, row, col;
int length = sizeof(a)/sizeof(int);
int bmat[length][10];
int c[10];
for(m=1;m<=d;m++)
{
for(i=0;i<10;i++)
{
c[i]=-1;
}
for(i=0;i<length;i++)
{
digit=(a[i]/e)%10;
c[digit]++;
row=c[digit];
col=digit;
bmat[row][col]=a[i];
}
k=-1;
for(i=0;i<10;i++)
{
if(c[i]!=-1)
{
for(j=0;j<=c[i];j++)
{
k++;
a[k]=bmat[j][i];
}
}
}
e=e*10;
}
cout << endl;
cout << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
cout << a[i] << " , ";
}
cout << endl;
system("pause");
return 0;
}
//Use this code
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter number of element:";
cin >> n;
//Data Structure
std::vector<int> list;
//push back element in vector
for(register int i=0;i<n;++i)
list.push_back(rand()%10 + 1);
//do shuffling before sorting because rand() generates increasing order number
std::random_shuffle(list.begin(),list.end());
std::sort(list.begin(),list.end());
ofstream textfile;
textfile.open ("E:\\example.txt");
for(size_t i= 0;i<list.size();++i)
textfile << list[i] <<" ";
textfile.close();
}
If you can write the sorted array to std::cout, then you can write it to a file. In C++, the console is the same as a file.
Put this at the end of main:
cout << "Sorted array:" << endl;
print_array( std::cout, a, n ); // Show the results to the user.
std::ofstream save( "array.txt" ); // Open a new file (or overwrite).
print_array( save, a, n ); // Save the results for later.
system("pause");
return 0;
}
and put the printing code in a new function, which may be defined before main:
void print_array( std::ostream & s, int * a, int n ) {
for(int i=0;i<n;i++)
{
s << a[i] << " , ";
}
s << endl;
}
#include<iostream>
#include<fstream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y){
return(x > y);
}
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void display(int array[], int n){
for (int i = 0; i<n; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void writeToFile(int array[], int n){
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
}
void sort(int table[], const int n) {
for (int i = 0; i < n; i++){
for (int j = 0; j < n - 1; j++) {
if (compare(table[j], table[j + 1]))
swap(&table[j], &table[j + 1]);
}
}
}
int main(){
int quantity;
int* tab;
ofstream outfile;
cout << "Enter number of element: ";
cin >> quantity;
tab = new int[quantity];
cout << "Element:\n\n" << endl;
for (int i = 0; i < quantity; i++){
int x = i;
cout << "#" << ++x << ":";
cin >> tab[i];
}
sort(tab, quantity);
cout << "The Sorted Elements are: ";
display(tab, quantity);
writeToFile(tab, quantity);
cout << endl;
getchar();
getchar();
//system("pause");
return 0;
}
in short, add this block to your code:
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
You can use C++ fstream class, since you want to output, you can use ofstream here. You should just replace some "cout" with ofstream instance:
At the beginning of the code state it:
ofstream ofs("./sorted_elem.txt", ofstream::out);
When want to output:
ofs << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
ofs << a[i] << " , ";
}
ofs << endl;
In C++ you really want to use std::vector or some other nice container for storing arrays of numbers. For writing an array to file you need to open the file and individually write each element to the file (all untested).
#include <fstream>
int main()
{
std::ofstream fp("output.txt");
int data[5]; // todo: fill
for (unsitned i = 0; i < 5; ++i)
{
fp << data[i] << ' ';
}
}
And to read again:
#include <fstream>
int main()
{
std::ifstream fp("output.txt");
// todo: Determine the size of the array or guess it (don't guess it!)
unsigned array_size = 5;
int data[array_size];
int n = 0;
while (fp.good() && n < array_size) fp >> data[n++];
}
But because we are using C++, we can use std::vector:
#include <fstream>
#include <vector>
int main()
{
std::vector<int> me(5); // todo: fill
std::ofstream fp("output.txt");
for (size_t i = 0; i < me.size(); ++i) fp << me[i] << ' ';
// C++11: for (int d : me) fp << d << ' ';
}
And,
#include <fstream>
#include <vector>
int main()
{
std::ifstream fp("output.txt");
std::vector<int> data;
double buf;
while (fp >> buf) data.push_back(buf); // no longer need to guess
}
I think, the copy option was not demonstrated here so far.
Please check this code. (Assuming your vector is ready to use, I've skipped it).
The example uses a C-array and a vector. Please use the later in your code whenever possible. But however, for copy-function both work:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
int main () {
int a[10]={0,1,2,3,4,5,6,7,8,9};
std::vector<int> v; for (int i=0; i<10; ++i)v.push_back(i*10); //0, 10, 20,...
std::ofstream fs_a( "c:/temp/out_a.txt" );
//store space separated
std::copy ( a, a+sizeof(a)/sizeof(a[0]), std::ostream_iterator<int>( fs_a, " ") );
//store coma-separated, as one-liner
std::copy ( v.begin(), v.end() ), std::ostream_iterator<int>( std::ofstream( "c:/temp/out_v.txt" ), ",") );
return 0;
}

Segmentaton Fault

I was trying to work on a CodeChef problem (Problem Link :: http://www.codechef.com/problems/K2). The code should take in a input for each test case, process, display the result, before moving to the next testcase. But it is just taking inputs without any output.
I am unable to figure out the error as the g++ compiler isn't giving any.
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;
using std::string;
char baseArr[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
bool isPalin(string number)
{
int len=number.size();
bool flag=true;
for(int i=0; i<len/2, flag==true; i++)
{
if(number[i]==number[len-(i+1)])
continue;
else
{
flag=false;
}
}
return flag;
}
string baseChange(long int number, int base)
{
int i=1;
int rem=0;
string output =" ";
while(number>0)
{
rem=number%base;
number=number/base;
output=baseArr[rem]+output;
}
return output;
}
int main()
{
long int input;
int testcase;
string number;
int i;
bool palin=false;
scanf("%d", &testcase);
while(testcase--)
{
palin=false;
scanf("%ld", &input);
for(i=2; palin==false;i++)
{
{
palin=isPalin(baseChange(input, i));
}
}
printf("%d\n",i);
}
}
You assume that the maximum base will be 16, but this may not be the case. You are probably getting a segmentation fault for accessing baseArr beyond valid index. I have not thought of the solution, but I believe the actualy solution can be implemented without considering any character value for the digits.
A solution to the Palindrome problem:
#include <sstream>
#include <cstdlib>
bool test_palindrome(const std::string& value)
{
for (unsigned int i = 0; i < value.length() / 2; i++)
{
if (value[i] != value[value.length() - 1 - i])
return false;
}
return true;
}
std::string find_palindrome(unsigned long num)
{
std::string ret = "";
for (int i = 2; i <= 32; i++)
{
char buffer[100] = {0};
std::string value = ::itoa(num, buffer, i);
std::cout << "Testing: Base=" << i << " Value=" << value << std::endl;
bool test = test_palindrome(value);
if (test)
{
std::stringstream ss;
ss << value << " (base " << i << ")";
ret = ss.str();
break;
}
}
return ret;
}
int main()
{
unsigned long input = 0;
std::cout << "Enter number to search: ";
std::cin >> input;
std::string palin = find_palindrome(input);
std::cout << std::endl << "Palindrome Found: " << palin << std::endl;
return 0;
}

Simple Array Coordinate Display Matching

I am attempting to create an array which takes user input and breaks at 99 99 but the multidimensional array does not stop taking inputted values. Another issue is getting the values to display on the grid down below in the visual representation. If more clarification is needed, please let me know.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int organisms[22][22];
int rows,
columns;
int input[22][22];
int *output = new int[];
//filling array
for(int i=0;i<22;i++)
{
for(int j=0;j<22;j++)
{
organisms[i][j]=0;
}
}
//column output
cout<<"\t\t\t\t\t\t\t\t\t\t\t\t\tColumn\n\n";
for(columns=1;columns<21;columns++)
{
cout<<"\t"<<columns;
}
cout<<"\n\n\n";
//Row and data output
for(int i=0;i<20;i++)
{
cout<<"Row "<<i+1<<"\t";
for(int j=0;j<20;j++)
{
cout<<organisms[i][j]<<"\t";
}
cout<<endl;
}
cout<<"\n\n\n";
cout<<"Enter each cell in first colony use row space column Enter format, 3 4, for example.\nEnter 99 99 to end entries.\n";
//input of values
cin.ignore(4);
int m=0;
do
{
cin>>input[m][m];
m++;
if(input[m][m]!=99,99)
break;
}while(m<20);
/*
while(input[m][m]!=99,99)
{
cin>>input[m][m];
m++;
}
/*
for(int m=0;m<INT_MAX;m++)
{
cin>>input[m][m];
if(input[m][m]==99)
break;
}
*/
//input array indexing
//output array
cout<<"\n\n\n";
cout<<"\t\t\t\t\t\t\t\t\t\t\t\t\tColumn\n\n";
for(columns=1;columns<21;columns++)
{
cout<<"\t"<<columns;
}
cout<<"\n\n\n";
for(int i=0;i<20;i++)
{
cout<<"Row "<<i+1<<"\t";
cout<<endl;
for(int n=0;n<20;n++)
{
cout<<input[i][n]<<"\t";
}
cout<<endl;
}
cin.get();
cin.get();
return 0;
}
if(input[m][m]!=99,99)
your input is an array of int, 99,99 is not an int. use valid int value, 5555 for example, or simple 99
E.g)
#include <iostream>
#include <iomanip>
#include <utility>
#include <vector>
#include <iterator>
using namespace std;
const size_t size=20;
char table[size][size];
void table_clear(void){
for(int v = 0; v<size; ++v)
for(int h = 0; h<size; ++h)
table[v][h]=' ';
}
void table_put(pair<int, int> p){
int v = p.first;
int h = p.second;
table[v-1][h-1] = '*';//to zero origin
}
void table_disp(){
cout << " ";
for(int i=0; i<size;++i){
cout << setw(3) << i + 1;
}
cout << "\n" << endl;
for(int i=0;i<size;++i){
cout << setw(3) << left << i + 1;
for(int j=0;j<size;++j){
cout << setw(3) << right << table[i][j];
}
cout << endl;
}
}
int main(){
vector<pair<int,int> > v;
pair<int, int> end(99,99);
pair<int, int> rc;
cout << "Enter each cell in first colony use row space column Enter format, 3 4, for example.\n";
cout << "Enter 99 99 to end entries." << endl;
while(true){
int row, column;
cin >> row;
cin >> column;
rc = make_pair(row, column);
if(rc == end)
break;
v.push_back(rc);
}
table_clear();
for(vector<pair<int,int> >::const_iterator iter = v.begin();iter != v.end(); ++iter ) {
table_put(*iter);
}
table_disp();
}

Longest Common Subsequence Length function not returning the correct length?

I have attempted to implement the dynamic programming approach to finding the longest common sub sequence between two sequences. My algorithm works when the two strings that are being compared are the same lengths, but when the second string is longer than the first, my LCSLength() function does not return the correct value.
Here is code with a test case that returns the wrong value.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int LCSLength(string X,string Y);
int main()
{
string first ("HELLO");
string second ("HLOCKKE");
int LCS;
//ifstream inData;
//inData.open("test.dat");
//inData >> first >> second;
//inData.close();
LCS = LCSLength(first,second);
cout << "The LCS is: " << LCS << endl;
cout << first << endl;
cout << second << endl;
return 0;
}
int LCSLength(string X,string Y)
{
int m = X.size();
int n = Y.size();
int C[m][n];
for(int i=0; i<=m; i++)
{
for(int j=0; j<=n; j++)
C[i][j] = 0;
}
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
if(X[i-1]==Y[j-1])
C[i][j]=C[i-1][j-1]+1;
else
C[i][j]=max(C[i][j-1],C[i-1][j]);
}
}
return C[m][n];
}
This should print "The LCS is: 3" because the LCS between my two strings is 3, however, my program does not. I can't find my error. Thank you for your help.
Fixed my errors using some google searches. Indexing was my problem. Here is the correct code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int LCSLength(string X,string Y);
int main()
{
string first ("HELLO");
string second ("HLOCKKE");
int LCS;
//ifstream inData;
//inData.open("test.dat");
//inData >> first >> second;
//inData.close();
LCS = LCSLength(first,second);
cout << "The LCS is: " << LCS << endl;
cout << first << endl;
cout << second << endl;
return 0;
}
int LCSLength(string X,string Y)
{
int m = X.size();
int n = Y.size();
int L[m+1][n+1];
for(int i=0; i<=m; i++)
{
for(int j=0; j<=n; j++)
{
if(i==0 || j==0)
L[i][j] = 0;
else if(X[i-1]==Y[j-1])
L[i][j] = L[i-1][j-1]+1;
else
L[i][j] = max(L[i-1][j],L[i][j-1]);
}
}
return L[m][n];
}