Data input from the keyboard.The length of array maybe very long.
I want to finish inputing when press ENTER twice.
the numbers separated by space, tab or ",". how to detect the length n?
I have tried like this:
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
void main()
{
bool flag=true;
unsigned n=0,i;
double x;
string line,str;
istringstream iss;
cout<<"input your numbers."<<endl;
count<<"Press the Enter key twice finish data inputting."<<endl;
while(flag)
{
getline(cin,line);
str+=line+' ';
if(line.empty())
flag=false;
}
// get the length n
iss.str(str);
while(iss>>x)
{
n++;
}
double *v=new double[n];
iss.seekg(0);
for(i=0;i<n;i++)
iss>>v[i];
for(i=0;i<n;i++)
{
cout<<v[i];
if(i<n-1)
cout<<' ';
}
cout<<endl;
delete []v;
}
I am a novice. Help me, Please!
Try this After taking the input in variable line do this:
#include<iostream>
#include<string>
#include<sstring>
using namespace std;
void main()
{
bool flag=true;
unsigned n,i=0;
double x;
string line,str;
istringstream iss;
cout<<"input your "
getline(cin,line);
int c=0;
char * pch;
pch = strtok (line," ,");// this will work for space and comma but you can add your own specifiers
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,");
c++;
}
return(c);// will give the length of arry.
}
Man to declare 1D array
the syntax is
void main()
{
int array[5];
//to initalize;
for(int i=0;i<5;i++)
{
array[i]=i;
}
for(int i=0;i<5;i++)
{
cout<<array[i]<<" ";
}
// and to declare dynamically
int * array=new int[5];
}
I have solved this problem.
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
void main()
{
bool flag=true;
unsigned n=0,i;
double x;
string line,str;
istringstream iss;
cout<<"input your numbers."<<endl;
cout<<"Press the Enter key twice finish data inputting."<<endl;
//Brecause data may come from clipboard and have multi line.
while(flag)
{
getline(cin,line);
str+=line+'\n';
// vc++ 6.0 have a bug in include file: STRING. You shoud fix it.
//Or you shoud press ENTER more than twice to terminate inputing.
//Replace I.rdbuf()->snextc(); to _I.rdbuf()->sbumpc();
if(line.empty())
flag=false;
}
// get the length n
iss.str(str);
while(iss>>x)
{
n++;
}
double *v=new double[n];
iss.clear();// very important.
// initialize v[n]
iss.str(str);
for(i=0;i<n;i++)
iss>>v[i];
// output v
for(i=0;i<n;i++)
{
cout<<v[i];
if(i<n-1)
cout<<' ';
}
cout<<endl;
delete []v;
}
Related
I need to be able to read in (first number is meant to be id number followed by transactions, making bank statement code, d means deposit, w is withdrawal, numbers after are amount):
123 d45.10 d50.45 d198.56 w45.67
345 w34.00 d4.56 w45.13 d23.23 w23.12
639 d1000.34 d1234.56 w34.33 w345.87 w22.13
890 d345.67 d123.67 d45.99 d45.99 w34.77
666 d66.60 d666.66 d6.66 d66.6 d6666.66
and have it sort into different arrays all stored within a struct. I have tried string stream and various other things i thought of, I'm like medium versed in c++, in the first year class to be specific.
This is the code I have so far, The first set of read ins is working properly but I cannot get the second one to work:
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
struct PersonAcct {
int acct_num[5];
string name[5];
double acct_bal[5];
};
struct PersonTrans {
int acct_num[5];
double trans[20];
char d_p[20];
};
int main() {
ifstream ifacc("accounts.txt");
PersonAcct p;
if (ifacc.is_open()) {
for (int i = 0; i <= 4; i++) {
ifacc >> p.acct_num[i];
ifacc >> p.name[i];
ifacc >> p.acct_bal[i];
}
}
ifacc.close();
ifstream iftrans;
iftrans.open("transactions.txt");
PersonTrans q;
string line,line2,line3,line4,line5;
if (iftrans.is_open()) {
int counter = 0;
while (getline(iftrans,line)) {
cout << line << endl;
counter++;
}
}
return 0;
}
Any help would be much appreciated! As I said before I am pretty new in retrospect to most of you on here so please be detailed or explain it for someone a bit daft in this subject, as I prob could be considered. I thank you and wish you a happy early holiday season!
If I understand you correct, you need to parse different words in different lines. You should be able to get this done easily with std::stringstream.
e.g.
...
iftrans.open("transactions.txt");
if (iftrans.is_open())
{
int counter = 0;
string line;
while (getline(iftrans, line)) // iterate through lines
{
int id;
string word;
stringstream ss(line);
ss >> id; // first word is the ID
while (ss >> word) // iterate though words of current line
{
switch (word[0]) // a word starts with either `w` or `d`
{
case 'w':
{
// remaining characters represent a valid double
double const val = stod(word.substr(1));
// process withdrawal
// ...
break;
}
case 'd':
{
double const val = stod(word.substr(1));
// process deposit
// ...
break;
}
default: break; // error?
}
}
counter++;
}
}
You may need to do additional error handling if the commented assumptions are not guaranteed to be valid always.
So I probably implemented it stupidly but here's what I thought you should do. Since the first thing will always be an ID I added that to acct_num;
Next I have a while loop for the line, I create a new string stream (Probably bad form, unsure) using a substring of everything after the first letter. Then I check the first letter of each transaction whether or not its a d or a w and put them into arrays. I had two counters for the w and d arrays. If they were vectors this wouldn't be necessary.
I wasn't sure what your original struct meant so I just created an array for deposits and withdrawals.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
struct PersonTrans {
int acct_num[5];
double deposits[20];
double withdrawals[20];
};
int main() {
ifstream iftrans;
iftrans.open("transactions.txt");
PersonTrans q;
if (iftrans.is_open()) {
int i = 0;
int d = 0;
int w = 0;
string line;
while (getline(iftrans,line)) {
stringstream in(line);
string tmp;
int idNumber;
in >> idNumber;
q.acct_num[i] = idNumber;
while(in >> tmp) {
double value;
std::stringstream transaction(tmp.substr(1));
transaction >> value;
if (tmp[0] == 'd'){
q.deposits[d] = value;
d++;
}
else if (tmp[0] == 'w'){
q.withdrawals[w] = value;
w++;
}
}
i++;
}
}
for(int i = 0; i < 20; i++){
cout << q.deposits[i] << endl;
}
return 0;
}
im doing an assignment for my lab which has to do with encrypting a string into a text file from another file, and it works good but my only problem is that when i encrypt or decrypt the encryption omits the letter Z and Y. I've tried changing a couple of things but nothing works, please if you know how to explain because i am lost.
this is my code so far:
#include iostream
==
#include fstream
==
#include cstring
==
#include string
==
using namespace std;
int main()
{
ifstream inputFile;
ofstream outputFile;
const int SIZE=150;
char file[SIZE];
char message[SIZE+1];
char letter;
char alphabet[]={'A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','\0'};
cout<<"Enter the message you want to encrypt: "<<endl; //getmessage
cin.getline(message,SIZE,'\n');
for(int i=0;i<strlen(message);i++){
if(islower(message[i])) //change to
message[i]=toupper(message[i]); //uppercase
}
outputFile.open("textoNoEncrypt.txt");
for(int i=0;i<strlen(message);i++){ //copy message to
outputFile.put(message[i]); //file
}
outputFile.close();
inputFile.open("textoNoEncrypt.txt");
if (inputFile.is_open()){
int i=0;
while (!(inputFile=='\0')){
inputFile>>file[i]; //reading and copying
i++; //data from file
}
}
inputFile.close();
outputFile.open("textoEncrypt.txt");
for(int i=0;i<strlen(file);i++){
int j=0;
int P=0;
int index=0;
bool found=false;
while(!found){
if(file[i]==alphabet[j]){
P=j;
index=(P+3)%26; //encrypting message
file[i]=alphabet[index];
found=true;
cout<<j<<" ";
}
j++;
}
outputFile.put(file[i]);
}
outputFile.close();
cout<<message<<endl; //show original message
cout<<file<<endl; //show encrypted message
return 0;
}
I think this is cause by the P+3 line
I have been scratching my head to figure out why is my program is crashing. My aim was to scan a string and get frequency of each sub string !
The Real part where the program is crashing (M is a map of string,int type)
My Input: the string is "abab" and the program crashes when i=0 and j is equal to 3 just at the M[e]++ statement!
for(i=0;str[i];i++)
{
char temp[5001];
k=0;
cout<<str[i]<<endl;
for(j=i;str[j];j++)
{
temp[k]=(char)str[j];
k++;
temp[k]='\0';
string e(temp);
M[e]++;
cout<<j<<endl;
}
}
MAIN Method
int main()
{
ini();
int t,N,i,j,Q,buff,k=0;
char str[5001];
scanf("%d",&t);
map <string ,int > M;
map <string , int >::iterator ii;
for(;t--;)
{
scanf("%d%d",&N,&Q);
scanf(" %s",str);
for(i=0;str[i];i++)
{
char temp[5001];
k=0;
cout<<str[i]<<endl;
for(j=i;str[j];j++)
{
temp[k]=(char)str[j];
k++;
temp[k]='\0';
string e(temp);
M[e]++;
cout<<j<<endl;
}
}
for(ii=M.begin();ii!=M.end();++ii)
F[ii->second]++;
F2[N]=F[N]%MOD;
for(i=N;i>=1;i--)
if(F[i])
for(j=i-1;j>=1;j--)
F2[j]=(F[j]+((long long)F[i]%MOD*C(F[i],j)%MOD)%MOD)%MOD;
for(i=0;i<Q;i++)
{
scanf("%d",&buff);
printf("%d\n",F2[buff]);
}
}
return 0;
}
Note
int F[5001],F2[5001];
are declared globally too.
As requested:
#include <iostream>
#include <string>
#include <map>
#define MOD 10
using namespace std;
int C( int a, int b ){
return 5;
}
int F[5001],F2[5001];
int main()
{
int t,N,i,j,Q,buff,k=0;
string str(5001, ' ');
cin >> t;//scanf("%d",&t);
cin.ignore( 256, '\n' );
map <string ,int > M;
map <string , int >::iterator ii;
for(;t--;)
{
cin >> N;
cin.ignore( 256, '\n' );
cin >> Q;
cin.ignore( 256, '\n' );
//scanf(" %s",str);
getline(cin,str);
for(i=0;str[i];i++)
{
char temp[5001];
k=0;
cout<<str[i]<<endl;
for(j=i;str[j];j++)
{
temp[k]=(char)str[j];
k++;
temp[k]='\0';
string e(temp);
M[e]++;
cout<<j<<endl;
}
}
for(ii=M.begin();ii!=M.end();++ii)
F[ii->second]++;
F2[N]=F[N]%MOD;
for(i=N;i>=1;i--)
if(F[i])
for(j=i-1;j>=1;j--)
cout << "hello";F2[j]=(F[j]+((long long)F[i]%MOD*C(F[i],j)%MOD)%MOD)%MOD;
for(i=0;i<Q;i++)
{
scanf("%d",&buff);
printf("%d\n",F2[buff]);
}
}
return 0;
}
For testing purposes, because there was no MOD and C definitions given, for MOD I used a constant int and C an empty function that received those parameters and simply returned a value.
Instead of scanf, I used cin for the inputs and later cin.ignore() to clear the input buffer so that it won't skip the next cin. Changed str to type string. Used getline to get input for string, as this reads the enitre line from the input cin. And that is it for modifications.
for(i=0;str[i];i++)
{
for(j=0;str[j+i];j++)
{
M[str.substr(j,i+1)]++;
}
}
Replace internal two for loops with this and check whether it's crashing or not . If still that means you may be running this program on windows.In that case use this.
for(i=0;str[i];i++)
{
for(j=0;str[j+i];j++)
{
std::string sstr = str.substr(j,i+1);
if ( M.find ( sstr ) == M.end() ){
M.insert( std::make_pair ( sstr , 0 ) ) ;
}
else
M[str.substr(j,i+1)]++;
}
}
## To check type of data entered in cpp ##
int main()
{
int num;
stack<int> numberStack;
while(1)
{
cin>>num;
if(isdigit(num))
numberStack.push(num);
else
break;
}
return(0);
}
If I declare a variable as interger, and I input an alphabet, say 'B', instead of the number, can I check this behavior of user? My code above exits when first number is entered and does not wait for more inputs.
First of all, the std::isdigit function checks if a character is a digit.
Secondly, by using the input operator >> you will make sure that the input is a number, or a state flag will be set in the std::cin object. Therefore do e.g.
while (std::cin >> num)
numberStack.push(num);
The loop will then end if there's an error, end of file, or you input something that is not a valid int.
First take your input as string
Using builtin libraries like isdigit() classify it as an integer
else if it contains '.'then its a float
else if it a alphanumerical the it is a string thats it
Code for this is below,
#include<iostream>
#include<string.h>
using namespace std;
int isint(char a[])
{
int len=strlen(a);
int minus=0;
int dsum=0;
for(int i=0;i<len;i++)
{
if(isdigit(a[i])!=0)
dsum++;
else if(a[i]=='-')
minus++;
}
if(dsum+minus==len)
return 1;
else
return 0;
}
int isfloat(char a[])
{
int len=strlen(a);
int dsum=0;
int dot=0;
int minus=0;
for(int i=0;i<len;i++)
{
if(isdigit(a[i])!=0)
{
dsum++;
}
else if(a[i]=='.')
{
dot++;
}
else if(a[i]=='-')
{
minus++;
}
}
if(dsum+dot+minus==len)
return 1;
else
return 0;
}
int main()
{
char a[100];
cin>>a;
if(isint(a)==1)
{
cout<<"This input is of type Integer";
}
else if(isfloat(a)==1)
{
cout<<"This input is of type Float";
}
else
{
cout<<"This input is of type String";
}
}
use cin.fail() to check error and clean the input buffer.
int num;
while (1) {
cin >> num;
if (cin.fail()) {
cin.clear();
cin.sync();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if (num == -1) {
break;
}
numberStack.push(num);
}
When I call the function and then display it, the output is same as the input. There is no other error in the program, which should mean taht there is some problem in the function. I'm just a beginner so any help is appreciated.
#include <iostream>
using namespace std;
struct student
{
char name[30];
int marks;
void getinfo()
{
cout<< "Enter your name:\n"; cin>>name;
cout<<"Enter marks:\n"; cin>>marks;
}
void showinfo()
{
cout<<"\nName: "<<name<<endl;
cout<<"Marks: "<<marks<<endl<<endl;
}
};
void bubsort( student S[] , int N)
{
student Temp;
for(int i=0;i<N-1;i++)
for(int j=0;j<N-1-i;j++)
{
if(S[j].name>S[j+1].name)
{
Temp=S[j];
S[j]=S[j+1];
S[j+1]=Temp;
}
}
}
int main()
{
student A[5];
cout<<" Enter details for 5 students:\n";
for( int i=0;i<5;i++)
A[i].getinfo();
bubsort(A,5); //I used the function
cout<<" Sorted information:\n";
for( int j=0;j<5;j++)
A[j].showinfo(); //result is in the same order as input
}
Arrays decays to pointers, so your comparison S[j].name>S[j+1].name is comparing pointers and not the strings.
If you want to compare string you need to use either std::string instead of character arrays, or use strcmp.