分开绳子并阅读每个部分
Splitting a String and Reading Every Part
本文关键字:个部 更新时间:2023-10-16
我正在尝试完成一个从文件读取并计算GPA的程序。基本上,每组有16组数据集,其中包含3种类型 - 名称,成绩和额外的积分。示例文本:
bugs兔子
a b b a- b b c a b a-
100
我遇到的问题是在获得等级时在字符串的中部。我正在尝试阅读整个成绩,然后阅读每个等级本身,例如" A"," B "。基本上读取" a",值为3,将其添加到累加器中,然后移至下一个字母等级,直到达到Newline字符为止。
我想到了使用.get,但这是为了吸收价值。我真的不明白如何从字符串中处理成绩。我知道使用了一个循环。
struct infoTaker
{
string theirName;
string theirGrade;
double theirDonation;
int totalValue;
};
int main( )
{
double donation;
char letter;
ifstream file;
string fullName, actualGrade, substring;
file.open("F://Yes/thing.txt");
for ( int i = 0; i < 16; i ++){
getline( file, fullName ); // getting the names
infoTaker person;
person.theirName = fullName;
cout << person.theirName << endl; // end of names section
getline(file, actualGrade); // gettting the entire line
person.theirGrade = actualGrade; // the string of grades
cout << letter << endl; // Don't know what to do here
file >> donation;
file.ignore( 3 , 'n');
person.theirDonation = donation;
cout << person.theirGrade << endl;
cout << person.theirDonation << endl;
double convertDoodahs = person.theirDonation / 2.0;
}
}
这是通过添加您在文件中读取的内容来完成此操作的一种方法,或者您也可以读取某些成绩。我猜这将更有用,因为然后您可以稍后检索名称和其他信息。
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
int main(){
std::vector<std::string> vec;
std::string temp;
std::string grades;
std::ifstream input("test.txt");
//add them to vector, and access them later
while(getline(input, temp)) vec.push_back(temp);
//read the grades and seperate them
std::stringstream ss(vec[1]);
while(ss >> grades){
std::cout << grades << "n";
}
}
示例txt文件
Bugs Bunny
A B C D+
100
输出
A
B
C
D+
#include<iostream>
#include<string>
using namespace std;
int convert(char a,char b=' ')
{
int result = 0;
if(b == ' ')
{
switch(a)
{
case 'A':
result = 9;
break;
case 'B':
result = 9;
break;
case 'C':
result = 9;
break;
}
}else
{
switch(a)
{
case 'A':
if(b=='+')
result = 10;
else
{
result = 8;
}
break;
case 'B':
if(b=='+')
result = 10;
else
{
result = 8;
}
break;
case 'C':
if(b=='+')
result = 10;
else
{
result = 8;
}
break;
}
}
return result;
}
int getSum(string g)
{
int ans = 0;
int l = g.length();
for(int i=0;i<l;)
{
char a = g[i++],b=' ';
if(g[i]=='+'||g[i]=='-')
{
b = g[i++];
}
ans+=convert(a,b);
i++;
}
return ans;
}
int main()
{
string g = "A B+ B A- B B C+ A B A-";
int sum = getSum(g);
}
尝试这个...
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 处理多个异常集合的C++方法
- 什么时候在C++中返回常量引用是个好主意
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 尝试通过多个向量访问变量时,向量下标超出范围
- Ardunio UNO解决了多个重叠的定时器循环
- 如何返回一个类的两个对象相加的结果
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 数到第n个楼梯的路(顺序无关紧要)
- 基于多个条件处理地图中的所有元素
- 为多个会话保留XPtr
- 如何在C++中初始化嵌套类中的2个memeber
- 运算符C++ "delete []"仅删除 2 个前值
- 具有多个参数的部分类模板专用化