【发布时间】:2019-07-25 05:33:43
【问题描述】:
我一直在尝试从文件中取出 ip 地址以及其他一些参数。在开始时我想提一下,我的积分不到 10 分,而且我无法上传图片 - 这就是为什么我会提供图片链接。
这是我从中读取的配置文件的屏幕截图: https://pasteboard.co/IpyYdxd.png
我的代码将端口、数据报大小和传输速度作为 int 变量,在我的 udp 套接字实现中使用它们没有问题。但是,它不允许我使用 std::basic_string 类型的 GROUP 变量,因为它需要 const char* 变量。
这是我的控制台应用程序的视图: https://pasteboard.co/Ipza3hON.png
我尝试使用 value.c_str() 函数将字符串/整数转换为常量 char,但是出现了问题。
// FILE TO BE SEND
FILE *file_handler;
if((file_handler = fopen("output_file.dat", "rb")) == NULL)
{
printf("Error: unable to read file\n");
exit(-1);
}
char buf[DATAGRAM_SIZE];
int i = 0;
// CONFIGURATION FILE
std::ifstream cFile ("plik_konfiguracyjny.txt");
if (cFile.is_open()){
std::string line;
set_light_red // set color to light red
while(getline(cFile, line)){
line.erase(std::remove_if(line.begin(), line.end(), isspace),line.end());
if(line[0] == '#' || line.empty()){ // if line starts with # or is empty - ignore
continue;
}
auto delimiterPos = line.find("=");
auto name = line.substr(0, delimiterPos);
auto value = line.substr(delimiterPos + 1);
printf(value.c_str()); // display received value from current line
printf("\n");
printf("zmienna i: %i\n",i); // display i to check what's the value in current loop
if(i == 0){
group = value.c_str(); // CONVERT STRING TO CONST CHAR*
}
if(i == 1){
port = std::stoi(value);
}
if(i == 2){
DATAGRAM_SIZE = std::stoi(value);
}
if(i == 3){
wait_for = std::stoi(value);
}
i = i +1;
}
set_white
printf("PARAMETRY TRANSMISJI ");
set_green
printf("ZALADOWANE\n\n");
set_white
}
else {
printf("PARAMETRY TRANSMISJI ");
set_red
printf("NIEZALADOWANE\n\n");
set_white
}
// create UDP with parameters from file
memset((char *) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(group);
addr.sin_port = htons(port);
没有错误,编译正常,但是它不会在给定文件中使用 ip 地址。
我的意思是用图片显示(以及出色的绘画技巧) https://pasteboard.co/IpzacMF.png
【问题讨论】:
-
首先请阅读how to ask good questions 和this question checklist。然后不要发布文本图像,将文本 as text 复制粘贴到问题中以使其独立。最后请learn how to debug your programs.
-
另外,请注意,不要使用索引号来检测配置文件中的数据类型。如果这样做,配置文件 always 需要以特定顺序记录其记录。取而代之的是配置的
name,使用它来决定值的用途。 -
请记住,本网站上的问题和答案不仅适用于您,也适用于现在或将来遇到相同或相似问题的每个人。现在想想如果您的问题中的链接消失了,或者内容更改为其他内容,会发生什么情况。这将使这个问题对未来的每个人都毫无价值。这就是为什么您应该阅读我在第一条评论中提供的链接,以便您了解如何在未来编写更好的问题(以及如何改进这个问题)。