Diese Präsentation wurde erfolgreich gemeldet.

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
×

1 von 2 Anzeige

# Write a function mostExpensive that- takes as argument a string- file.docx

Write a function mostExpensive that:
â€¢ takes as argument a string, filename, which is the name of a text file containing lines looking like this:
bicycle ??? dollars
â€¢ The function finds the most expensive item in the file and returns it (as a string).
For example, suppose that file \"inventory.txt\" has these contents:
bicycle 80 dollars
table 150 dollars
chair 40 dollars
watch 25 dollars
Then: mostExpensive(\"inventory.txt\") returns \"table\".
Solution
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
string mostExpensive(char* filename){
ifstream infile;
infile.open (filename);
string s,smax,dollar;
int n,nmax;
infile>>smax;
infile>>nmax;
infile>>dollar;
while(infile>>s){
infile>>n;
infile>>dollar;
if(n>nmax){
nmax = n;
smax = s;
}
}
return smax;
}
int main(){
cout<<mostExpensive(\"inventory.txt\");
return 0;
}
.

Write a function mostExpensive that:
â€¢ takes as argument a string, filename, which is the name of a text file containing lines looking like this:
bicycle ??? dollars
â€¢ The function finds the most expensive item in the file and returns it (as a string).
For example, suppose that file \"inventory.txt\" has these contents:
bicycle 80 dollars
table 150 dollars
chair 40 dollars
watch 25 dollars
Then: mostExpensive(\"inventory.txt\") returns \"table\".
Solution
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
string mostExpensive(char* filename){
ifstream infile;
infile.open (filename);
string s,smax,dollar;
int n,nmax;
infile>>smax;
infile>>nmax;
infile>>dollar;
while(infile>>s){
infile>>n;
infile>>dollar;
if(n>nmax){
nmax = n;
smax = s;
}
}
return smax;
}
int main(){
cout<<mostExpensive(\"inventory.txt\");
return 0;
}
.

Anzeige
Anzeige

## Weitere Verwandte Inhalte

Anzeige

### Write a function mostExpensive that- takes as argument a string- file.docx

1. 1. Write a function mostExpensive that: â€¢ takes as argument a string, filename, which is the name of a text file containing lines looking like this: bicycle ??? dollars â€¢ The function finds the most expensive item in the file and returns it (as a string). For example, suppose that file "inventory.txt" has these contents: bicycle 80 dollars table 150 dollars chair 40 dollars watch 25 dollars Then: mostExpensive("inventory.txt") returns "table". Solution #include<iostream> #include<fstream> #include<string> using namespace std; string mostExpensive(char* filename){ ifstream infile; infile.open (filename); string s,smax,dollar; int n,nmax; infile>>smax; infile>>nmax;
2. 2. infile>>dollar; while(infile>>s){ infile>>n; infile>>dollar; if(n>nmax){ nmax = n; smax = s; } } return smax; } int main(){ cout<<mostExpensive("inventory.txt"); return 0; }