I am trying to get the long double out of an array.
long double num;
char * pEnd;
char line[] = {5,0,2,5,2,2,5,4,5,.,5,6,6};
num = strtold(line1, &pEnd);
For some reason the num i am getting is rounded to 502522545.6
I am quite new to C++ so is there something i am doing wrong ? What needs to be done to get the entire number in the num instead of the rounded up?
Thank you for the help !!!
Sorry that's my first post here =)
So the entire program code is as following :
class Number
{
private:
long double num ;
char line[19], line2[19];
int i, k;
public:
Number()
{}
void getData()
{
i = 0;
char ch= 'a';
cout << "\nPlease provide me with the number: ";
while ((ch = _getche()) != '\r')
{
line[i] = ch;
line2[i] = ch;
i++;
}
}
void printData() const
{
cout << endl;
cout << "Printing like an Array: ";
for (int j = 0; j < i; j++)
{
cout << line[j];
}
cout << "\nModified Array is: ";
for (int j = 0; j < (i-k); j++)
{
cout << line2[j];
}
cout << "\nTHe long Double is: " << num;
}
void getLong()
{
char * pEnd;
k = 1;
for (int j = 0; j < i; j++)
{
if (line2[j+k] == ',')
{
k++;
line2[j] = line2[j + k];
}
line2[j] = line2[j + k];
}
line2[i -k] = line2[19];
num = strtold(line2, &pEnd);
}
};
int main()
{
Number num;
char ch = 'a';
while (ch != 'n')
{
num.getData();
num.getLong();
num.printData();
cout << "\nWould you like to enter another number ? (y/n)";
cin >> ch;
}
return 0;
}
The idea is that the number entered is in the following format ($50,555,355.67) or any other number. The program then removes all signs apart of numbers and "."
Then i tried to get the long double num out of an array.
If you run the program you always get the rounded number from num.
The C++ way of doing this is pretty simple:
#include <sstream>
#include <iostream>
#include <iomanip>
int main() {
const std::string line = "502522545.566";
long double num;
std::istringstream s(line);
s >> num;
std::cout << std::fixed << std::setprecision(1) << num << std::endl;
}
Using modern C++ you can simply do:
auto line = "502522545.566"s;
auto num = std::stold(line);
Live example
Theres probably a more C++ way, but sscanf will work:
const char *str = "3.1459";
long double f;
sscanf(str, "%Lf", &f);
Related
Hello so I've seen some other posts about it but they never seem to solve my issue, or I just can't understand it with my peanut sized brain.
If I input something, and push it back to the vector, it would always have some stupidly absurd number(s)
For those who want context or in case it's outside of what I think is the problem, here's the full code:
#include <iostream>
#include <string>
#include <array>
#include <algorithm>
#include <vector>
using namespace std;
void stringToVec(string input, vector<int> output)
{
int e = 0;
string temp;
//cout << "size: " << input.size() << '\n';
for(int i = 0; i < input.size(); i++)
{
if(input[i] != ' ')
{
temp += input[i];
}
else if(input[i] == ' ')
{
int num = stoi(temp);
output.push_back(num);
temp = ""; // clear temp
}
}
}
int main()
{
int a, b;
string numsIn1, numsIn2;
cin >> a;
cin >> ws;
getline(cin, numsIn1);
numsIn1 += ' ';
int nums1[a];
// =======================
cin >> b;
cin >> ws;
getline(cin, numsIn2);
numsIn2 += ' ';
int nums2[b];
// =======================
vector<int> output;
stringToVec(numsIn1, output);
stringToVec(numsIn2, output);
int e = 0;
for(int i = 0; i < a; i++)
{
output.push_back(nums1[i]);
}
for(int i = 0; i < b; i++)
{
output.push_back(nums2[i]);
}
sort(output.begin(), output.end());
//int dyfslashj[3] = {3, 2, 1};
for(int i = 0; i < a + b; i++)
{
cout << output[i] << ' ';
}
return 0;
}
Here's the line thats most likely to be the problem. For example if I input the number "3 4 2" the vector would be like "5234523452345 32452 34523", or some absurd value
void stringToVec(string input, vector<int> output)
{
int e = 0;
string temp;
//cout << "size: " << input.size() << '\n';
for(int i = 0; i < input.size(); i++)
{
if(input[i] != ' ')
{
temp += input[i];
}
else if(input[i] == ' ')
{
int num = stoi(temp);
output.push_back(num);
temp = ""; // clear temp
}
}
}
maybe there are something wrong with your "cin". I can see you used cin and getline. But getline will read at the first line.No matter it have been "cin".you can try to use some strings as parameter to the function to see whether it's correct or not
I'm trying to create a program where you input 20 characters into an array. Each time you enter a new character, the program should check if that character is already in the array, if it is, print duplicate (but still add the duplicate to the array)
For example, if user types 'a', program should check if 'a' is inside the array.
This is my code:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i= 0; i <= 20; i++) {
cin >> input;
for (int k = 0; k <= 20; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
myAlpha[i] = input;
}
}
I just can't figure out how to make it work, I'm probably missing something stupid. The solution must use something like the code above, no fancy functions or anything.
EDIT: Fixed Code:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i= 0; i < 20; i++) {
cin >> input;
for (int k = 0; k < i; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
myAlpha[i] = input;
}
}
Only problem is that "duplicate" is printed a extra time for each duplication of a letter. For example, if 'a' is entered 3 times, on the 3rd time, "duplicate" is printed 2 times. And so on. But not a big deal.
try this:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i = 0; i < 20; i++) {
cin >> input;
myAlpha[i] = input;
for (int k = 0; k < i; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
}
}
With this line:
char myAlpha[20];
The valid indices of that array are from 0 to 19. However, this line:
for (int i= 0; i <= 20; i++) {
Already implies a bug. Change it to this:
for (int i= 0; i < 20; i++) {
Do the same treatment for the inner for loop line: for (int k = 0; k <= 20; k++) {
But... you'll also need to keep track of how many characters have been inserted instead of looping up to 20 again.
So this is closer to what you want:
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
int inserted = 0;
while (inserted < 20) {
cin >> input;
bool duplicate = false;
for (int k = 0; k < inserted; k++) {
if (myAlpha[k] == input) {
cout << "Duplicate" << endl;
duplicate = true;
break; // no point in continuing to look for duplicates once the first one is found
}
}
if (!duplicate) {
myAlpha[inserted] = input;
inserted++;
}
}
}
Even faster and you can avoid the inner for-loop:
int main() {
bool duplicates[256] = {};
char myAlpha[20] = {};
char input;
cout << "Enter a letter" << endl;
int inserted = 0;
while (inserted < 20) {
cin >> input;
bool duplicate = duplicates[(unsigned char)input];
if (duplicate) {
cout << "Duplicate" << endl;
}
else {
myAlpha[inserted] = input;
inserted++;
duplicates[(unsigned char)input] = true;
}
}
}
I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:
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)
#include <string.h>
#include "BubbleSort.h"
void BubbleSort(char Str[])
{
int i;
int NumElements;
bool Sorted;
char Temp;
NumElements = strlen(Str);
do {
Sorted = true;
NumElements--;
for (i = 0; i < NumElements; i++)
if (Str[i] > Str[i + 1])
{
Temp = Str[i];
Str[i] = Str[i + 1];
Str[i + 1] = Temp;
Sorted = false;
}
} while (!Sorted);
}
/////////////////////////////////////////////
#include <iostream>
#include "Bubblesort.h"
using namespace std;
void main() {
int Num;
char Array[20];
cout << "How many numbers would you like to enter?" << endl;
cin >> Num;
cout << "Enter your numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cin >> Array[i];
}
cout << "Here are the numbers you entered:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl << endl;
BubbleSort (Array);
cout << "Here are your sorted numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl;
}
////////////////////////////////////////////////////////
#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
void BubbleSort(char[]);
#endif
I get a Run Time Error stating that Num was corrupted. Can anyone help pinpoint the problem in my code?
Thanks
char Array[20] while the Num you input is larger than 20, it will corrupt.
Better use vector and push_back
One mistake is that you're calling strlen on a char array that is not guaranteed to be NULL terminated:
NumElements = strlen(Str);
Thus NumElements has an undetermined value.
You need to either:
1) pass the actual number of characters that are to be sorted as a parameter, along with the array and getting rid of the call to strlen:
BubbleSort(Array, Num);
//...
void BubbleSort(char Str[], int NumElements)
or
2) Make sure the char array you're passing is null terminated