gpt4 book ai didi

C++一次给两个字符串赋值

转载 作者:行者123 更新时间:2023-11-28 08:21:40 26 4
gpt4 key购买 nike

    unsigned short n = 0;
while (!in.eof())
{
in >> opString; //Read in string from file
//Read the string from file character by character
for (int i = 0; i < opString.size(); i++)
{
if (!op1b) //If we do not yet know our first operand (op1b = false, b stands for bool, clever naming eh?)
{ //Check if our next item is an operator. If it is...
if (!(opString[i] == '+' || opString[i] == '-' || opString[i] == '*' || opString[i] == '/' || opString[i] == '$'))
op1[i] = opString[i];
else //We finally know it since when we hit an symbol, our first number is known; do not repeat this if block
op1b = true;
n++;
}

if (op1b && !operb) //If we know our first operand but not our operator...
{
oper = opString[i]; //Find out what our operator is. Now we know it (operb = true)
operb = true;
i++; //We increment i because if we did not we'd double dip on the if statement below and wind up
} // with an operator tacked onto the beginning of the second operand

if (op1b && operb) //If we know our first operand and the operation, let's find operand #2
{
if (opString[i] == '=')
break;
else
{
op2[i-n] = opString[i];
j++;
}
}
}
cout << "Op 1: " << op1.c_str() << endl << "Oper: " << oper.c_str() << endl << "Op 2: " << op2.c_str() << endl;
}
return 0;
}

我这里有一个程序(的开头),该程序旨在从文本文件中读取字符串以将十六进制操作数相加。字符串的形式为“op1OperatorOp2=”(减去引号)。我才刚刚开始。我试图通过逐个字符地从文件 (opString) 中读取字符串(如 for 循环中的 i 所示),从中取出 op1、op2 和运算符(所有字符串)。 while 循环只是检查它不是 fstream 变量的文件结尾。 op1b 和 operb 是 bool 值,有助于确定我们何时“知道”我们的第一个操作数和运算符是什么(然后我们何时可以找出第 2 个运算符)。

但是,当我从字符串中提取 op2 时,我的 op1 会被 op2 的值替换,即使我只说 op2[whatever] = opString[i] 而 i 远远超过了 op1 所在的位置。

示例:如果来自文件的字符串是“3+2=”,则 op1 应该得到 3,op 应该得到 +,op2 应该得到 2。但是,op2 最终总是与 op1 在循环结束。因此,我最终得到的不是 op1 = 3, oper = +, op2 = 2,而是 op1 = 2, oper = +, op2 = 2。

是否缺少某些未记录的 C++ 功能?我不知道为什么会这样。是因为我在循环中吗?我应该打破我的循环吗?但是,我不明白为什么这会有所作为。谢谢。

最佳答案

下次发布完整代码(包含所有声明)。 op1op2 是std::string?您尝试在 op1op2 中写入字符,但您没有分配任何空间,即您应该在 op1.resize(SOME_SIZE) 之前循环或使用 std::string::push_back 将字符附加到操作数。

关于C++一次给两个字符串赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5609791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com