现有一个文件input.txt,内容如下: N=x(x为从2到100的随机数字) 请编写一段c++代码,定义一个int型变量n,将“N=”后面的数字赋值给n
时间: 2024-04-14 10:29:29 浏览: 89
利用c++在一个文件中产生随机数
Sure! Here's a C++ code snippet that reads the input.txt file, extracts the value after "N=", and assigns it to an integer variable n:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile("input.txt");
std::string line;
if (inputFile.is_open()) {
while (std::getline(inputFile, line)) {
size_t found = line.find("N=");
if (found != std::string::npos) {
int n = std::stoi(line.substr(found + 2));
std::cout << "n = " << n << std::endl;
break;
}
}
inputFile.close();
} else {
std::cout << "Unable to open input.txt file" << std::endl;
}
return 0;
}
```
This code opens the input.txt file, reads it line by line, and searches for a line containing "N=". If found, it extracts the value after "N=" using substr() function and converts it to an integer using stoi() function. Finally, it assigns the value to the variable n and prints it.
阅读全文